Week 4 Review — Exceptions
Goal
This review checks whether I can name a failure, keep the cause, close what I opened, and map it once at the edge.
Week 4 topics:
Throwable/Error/ checked / uncheckedthrow,throws,catchorder, cause- Try-with-resources, suppressed,
finally - Domain exceptions and translation
- REST mapping and
@Transactionalrollback
1. Week 4 big picture
OrderService.place
throws OrderNotFoundException / DuplicateOrderException (unchecked)
│
│ @Transactional: rollback on those runtime types
▼
RestExceptionHandler (@ControllerAdvice)
maps type → HTTP 404 / 409 / ProblemDetail
logs once
Persistence adapter
SQLException → DataAccessException → DuplicateOrderException (cause kept)
Import job
try (InputStream in = ...) { ... } // I opened it, I close it
2. Core memory sentences
Erroris the JVM.RuntimeExceptionis unchecked. OtherExceptiontypes are checked.
throwunwinds.throwsdeclares a checked contract.
Catch specific before general. Empty catch is a production bug.
Wrap with the cause. Do not keep only the message.
Prefer try-with-resources;
finallyis for non-closeable cleanup.
Close what I opened. Do not close the container’s
EntityManager.
Name the business failure. Translate once at the adapter edge.
Services throw domain types. The web layer chooses the status code.
Default rollback is unchecked. Checked commits unless
rollbackFor.
3. Speak these without notes
- Checked vs unchecked, and what a REST service throws.
- Why Spring invented
DataAccessException. - Body vs
close()both throw — which one does the caller see? - Why
returninfinallyis a bug. @Transactionalplus a checked exception: commit or rollback?
4. Tiny code proofs
Proof A — catch order
Throw FileNotFoundException into catch (IOException) vs a prior catch (FileNotFoundException). Confirm first-fit.
Proof B — suppressed
An AutoCloseable whose close() throws, body also throws. Print getSuppressed().
Proof C — wrap with cause
Catch IOException, throw UncheckedIOException("read failed", e), then printStackTrace() and find both.
5. Common mix-ups from this week
| Mix-up | Clear line |
|---|---|
| Checked is morally better | Checked is a compiler contract; REST uses unchecked + mapping |
| Catch everything in the service | Catch at adapter or advice |
finally return is cleanup | It swallows the exception |
I close EntityManager | Spring opened it |
| Checked exception undoes the insert | Default @Transactional commits |
6. Interview drill
Open Java fundamentals:
- Checked vs unchecked — what should a REST service throw?
try-with-resourcesvsfinally
Then peek at REST and MVC when you want the HTTP side, and Spring book Week 4 Day 4 when you study MVC.
Use the four-part answer.
7. Ready for Week 5?
I am ready if I can draw the type tree, wrap with a cause, and say the transactional rollback default without hedging.
Week 5 is generics: erasure, wildcards, Optional as a return type.