Lesson · Exception Handling
Advanced exceptions: resources, suppressed, precise rethrow
17 min readAdvanced
try-with-resources closes in reverse order and folds close failures into suppressed exceptions; precise rethrow lets the compiler keep the narrowed type; and finally can still swallow the original failure if it throws.
Two failures, one catch block
The body throws, and on the way out the resource's close() throws too. Predict what the catch block sees:
try (FailingClose f = new FailingClose()) { throw new RuntimeException("primary"); } // catch (RuntimeException e): // e.getMessage() -> "primary" // e.getSuppressed()[0] -> the close failure, attached if close also fails
Predict: both failures survive. The primary exception propagates and the close failure is attached to it as a suppressed exception. That is why try-with-resources replaced hand-written finally: nothing gets lost, and nothing needs manual bookkeeping.
try-with-resources, rule by rule
The declaration can hold several resources, and their lifecycle is fully specified:
try (Latch a = new Latch("A"); Latch b = new Latch("B")) { System.out.println("body"); } // body runs, then: closed B, then closed A (reverse order)
- The resource type implements
AutoCloseable;close()runs no matter how the body exits, throw or return. - Resources close in reverse declaration order: the last opened is the first closed, like nested finally blocks.
- If the body throws and a close throws, the body's exception propagates with the close failure attached as suppressed.
- If the body succeeds and a close throws, that close exception propagates normally: there is no primary to attach it to.
- Pre-existing resources can be used directly if they are effectively final:
try (reader)re-uses the variable.
Reverse order is on purpose: later resources may depend on earlier ones, so the dependent closes first; the rule mirrors the construction order in the declaration list.
Resource lane · unwind order and suppressed failures
Current statement
Open resources (top closes first)
Output
nothing yet
Two resources are declared and opened in order: a (a normal latch), then f (whose close will fail). The stack is ready for the body.
Precise rethrow: the compiler keeps the narrow type
A catch that rethrows a broad Exception normally widens the method's throws list. Precise rethrow avoids that:
static void preciseRethrow() throws IOException { // only IOException can leave try { throw new IOException("io detail"); } catch (Exception e) { throw e; // analyzed: only IOException reaches here } }
- The compiler inspects what the try can actually throw (IOException here) and treats the rethrow as that narrow set.
- So the method keeps
throws IOException, and callers keep their precise catching; verified by compiling and running the demo. - The moment the try gains a second possible exception, the analysis grows and the signature must too: it is still static checking, not magic.
- This pattern (cleanup plus rethrow in a broad catch) is the legitimate reason
catch (Exception e) { throw e; }exists.
Precise rethrow is flow analysis applied to signatures. The compiler already knows the possible thrown set; the feature lets a broad catch clause rethrow without polluting every caller's throws obligations.
Multi-catch and the finally trap
Two more rules complete the picture:
- Multi-catch bundles unrelated types:
catch (IOException | ParseException e)shares one handler; the alternatives may not be related by subclassing (verified message:Alternatives in a multi-catch statement cannot be related by subclassing) and the parameter is implicitly final. - A throw in finally discards the original: verified: an original RuntimeException in the try is replaced by the IllegalStateException thrown from finally; the first failure never surfaces. This is the strongest reason to keep finally bodies to cleanup only.
- A return in finally does the same silently: it also replaces in-flight exceptions, which is why review checklists flag it (the basics lesson showed the mechanism).
- `Throwable.addSuppressed` is available to your own code too: try-with-resources is its main user, but any cleanup that fails alongside a primary failure can attach the secondary the same way.
Finally is for putting things back, not for outcomes. Throw, return, and even logging-from finally are all ways to overwrite the ending; resource management via try-with-resources removes nearly every legitimate reason to write that block by hand.
The advanced playbook
Handling failures with resources and rethrows, in order:
- Make cleanup objects
AutoCloseableand let try-with-resources own the whole lifecycle; do not hand-write the finally. - Expect reverse-order closing; arrange declarations so dependencies close in a valid order.
- When both body and close fail, read
getSuppressed(); the primary message alone tells half the story. - Use precise rethrow for cleanup-and-rethrow blocks; keep the signature narrow and let the compiler check the set.
- Ban throw and return inside finally in code review; keep multi-catch alternatives unrelated and the parameter untouched.
The construct finally grew into what people actually needed. Try-with-resources, suppressed exceptions and precise rethrow all replace folklore patterns with compiler-checked ones; the last lessons turn these rules into habits and traps.
Resources close in reverse order; failures ride together suppressed
try-with-resources closes declared resources last-in-first-out, run on every exit, and when the body and a close both fail, the close failure is attached to the primary as suppressed. Precise rethrow keeps signatures narrow for cleanup-and-rethrow blocks, and finally remains a place where throw and return silently replace the original outcome, so keep it for cleanup only.
Interview angles
How does try-with-resources decide which exception to throw?+
The body's exception is primary: it propagates, with any close failures attached as suppressed. If the body succeeds, a close failure propagates on its own.
The design keeps diagnostics complete: the caller sees the reason the operation failed, and the record still shows the cleanup failure that followed. Reading only the primary message in a bug report misses half the story; getSuppressed() has the rest.
catch (RuntimeException e) { e.getSuppressed()[0].getMessage(); // "close failed" }
Common misconception: That the last exception thrown wins. The body's failure is primary; close failures are attached to it.
Follow-up: When does a close failure become the primary exception?
In what order do declared resources close, and why?+
Reverse declaration order: the last opened closes first, mirroring nested finally blocks and respecting dependencies between resources.
A writer opened on a stream closes before the stream because it was declared after it. The declaration order is therefore an ordering decision, not a formatting one, and the compiler enforces the lifecycle you wrote.
try (Latch a = new Latch("A"); Latch b = new Latch("B")) { ... } // closes B, then A
Common misconception: That order is unspecified or alphabetical. It is strictly last-in-first-out.
Follow-up: What would break if a stream closed before the writer built on it?
What is precise rethrow and when does it matter?+
When a broad catch clause rethrows (catch (Exception e) { throw e; }), the compiler analyzes what the try can actually throw and lets the method keep the narrow throws type.
The pattern appears in cleanup-and-rethrow code, where you want one catch for all failures but must not widen every caller's obligations. Verified: a try that throws only IOException compiles with throws IOException despite the catch (Exception).
static void f() throws IOException { try { throw new IOException("x"); } catch (Exception e) { throw e; } // still only IOException in the signature }
Common misconception: That any rethrow of Exception requires declaring Exception. Only rethrows the compiler cannot narrow do.
Follow-up: What happens to the signature when the try gains a second checked failure type?
What do multi-catch rules forbid, and why?+
Alternatives related by subclassing: catch (IOException | FileNotFoundException e) is refused (verified message: Alternatives in a multi-catch statement cannot be related by subclassing), and the parameter is implicitly final.
The subclass alternative adds nothing the supertype does not already match, exactly like the unreachable-catch rule. The implicit finality keeps the handler honest: one variable, one value, no accidental reassignment mid-handling.
catch (IOException | ParseException e) { ... } // siblings: fine
Common misconception: That listing more types catches more. Overlapping types are refused at compile time; the union must be genuinely irreducible.
Follow-up: Which two earlier rules is this rule the multi-catch twin of?
Why is throwing from finally so dangerous?+
It replaces whatever the try was doing: an in-flight exception (or return) is discarded and the finally's exit takes over, losing the original failure silently.
Verified: a try that throws 'original' with a finally that throws 'from finally' surfaces only the latter; the first failure never appears in any log. The same shape applies to return-from-finally. Cleanup that cannot fail silently is the rule, and try-with-resources provides it.
try { throw new RuntimeException("original"); } finally { throw new IllegalStateException("from finally"); } // original is gone
Common misconception: That both exceptions are reported. Only the finally's escape survives, unless you attach the original yourself.
Follow-up: How would you write a cleanup that cannot erase the original failure?