Skip to main content
PreparationZone Logo
PrepZone

try, catch, finally and Resources

Multi-catch, try-with-resources, propagation, and the edge cases where finally surprises you.

Pass checkpoint below

Read these first

Why this matters

  • finally can 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 catch blocks is checked by the compiler in a way that trips people up exactly once.

The basic flow

try block starts
No — try completes
Yes — matching catch runs
finally always runsClose resources here
finally runs on every path — success, handled failure, or an exception on the way out. That is why cleanup belongs there, or better still in try-with-resources.
Java
Loading compiler…
  • Execution leaves the try block at the point of failure. The remaining statements in it are skipped.
  • The first matching catch runs, and only that one. There is no fall-through.
  • finally runs after the try and any catch, whether or not an exception occurred, and even on return.
  • If no catch matches, finally still 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.

Java
Loading compiler…
Java
Loading compiler…

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 |.

Java
Loading compiler…

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.