Why this matters
finallycan silently discard an exception or override a return value, and both produce bugs that are nearly impossible to spot by reading.- try-with-resources removed an entire category of resource leak and exception-masking bugs in one feature, and the manual equivalent is genuinely hard to write correctly.
- The order of
catchblocks is checked by the compiler in a way that trips people up exactly once.
The basic flow
- Execution leaves the
tryblock at the point of failure. The remaining statements in it are skipped. - The first matching
catchruns, and only that one. There is no fall-through. finallyruns after thetryand anycatch, whether or not an exception occurred, and even onreturn.- If no
catchmatches,finallystill runs and the exception then propagates to the caller.
Catch order is enforced
A catch matches the exception type or any subtype, so the most specific must come first.
The compiler rejects the second form outright, which is a rare and welcome case of a mistake being impossible to ship.
Multi-catch
When several exception types need identical handling, combine them with |.
The parameter is implicitly final, and its static type is the nearest common supertype — so inside
the block you can only call methods available on both.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 6 sections
- Precise rethrow (Java 7+)
- Exceptions when overriding
- finally, and its three surprises
- try-with-resources
- Propagation
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.