Lesson · Exception Handling
try, catch, finally: the control flow, step by step
16 min readBasics
Five keywords carry the whole mechanism: try marks the guarded region, catch intercepts by type from top to bottom, finally runs no matter how the region exits, throw starts an exception, and throws declares one to the caller.
Predict the order of the lines
One method, three blocks, one output. Predict the order before reading the answer:
static String sequence() { StringBuilder log = new StringBuilder(); try { log.append("try "); throw new IllegalStateException("boom"); } catch (IllegalStateException e) { log.append("caught:").append(e.getMessage()).append(" "); } finally { log.append("finally"); } return log.toString(); // predict: which order do the parts land in? }
Predict: try caught:boom finally. The throw leaves the try immediately, the catch matches by type, and the finally runs on the way out of the whole construct, whichever path the exit took.
The five pieces
The keywords and their jobs, one table:
| Piece | Job |
|---|---|
try { ... } | The guarded region: exceptions raised inside may be caught beside it |
catch (Type e) { ... } | Handles matching exceptions, tested top to bottom by instanceof |
finally { ... } | Runs as the region exits, whether by falling out, returning, or throwing |
throw x; | Raises an exception: from here, control unwinds to the nearest matching handler |
throws IOException | Declares to the caller that a checked exception may leave this method |
`catch` reads like an if-chain over types. The first clause whose type matches the thrown object wins; the rest of the chain is skipped. That single sentence predicts ordering, reachability and multi-catch rules.
How control leaves a try
Every exit follows the same shape: unwinding runs the finally, then control continues after the construct:
- Falling out normally: the finally runs, then the next line.
- Throwing: matching catch runs first, then the finally, then execution continues after the try.
- Returning from inside: the finally runs before the method actually returns.
- The two sharp edges: a
returninside finally overwrites any return or throw from the try (verified: the method returns 2, not 1), andSystem.exitskips finally entirely because the JVM stops (verified: nothing prints).
finally is for cleanup, not for control flow. Both sharp edges are reasons, not features: returning from finally silently discards exceptions, and no wrapper can run after System.exit.
Flow lane · try, catch, finally, after
Current statement
Output so far
…
The try block starts. It is the guarded region: everything inside may be intercepted by the clauses beside it.
Catch order, and the unreachable block
Because matching is top to bottom, a broader clause above a narrower one makes the narrower unreachable, and the compiler refuses it:
try { throw new IOException(); } catch (Exception e) { // everything, including IOException... } catch (IOException io) { // error: exception IOException has already been caught }
- Specific first, broad last: FileNotFoundException before IOException before Exception.
- The compiler's message names the dupe: the unreachable clause is a compile error, not a runtime surprise.
- Multi-catch bundles siblings, not ancestors:
catch (IOException | ParseException e)is fine; a type and its own supertype in one list is refused (the advanced lesson shows the message). - A catch that cannot be thrown is also refused when no reachable statement in the try can raise it: the compiler keeps the block honest from both sides.
Order is semantics. In an if-chain, order is a choice; here it decides whether code can ever run, and the compiler enforces it, which is a kindness in disguise.
The basics playbook
Writing try/catch/finally, in order:
- Keep the try block small: the guarded region should contain exactly the operations whose failure you are handling.
- Catch the most specific type that names the failure you can act on; let the rest propagate.
- Never leave a catch empty; if the failure truly needs no action, write the reasoning as a comment and log at the boundary above (next lessons).
- Use finally for cleanup until resources arrive (try-with-resources, two lessons ahead); never return from it.
- Declare checked exceptions you do not handle with
throws, and keep that list accurate.
Five keywords, one shape. Guarded region in, typed interception, unconditional exit, explicit raising, explicit declaration: once the flow is familiar, every exception-handling question becomes a variation of it.
try raises the region, catch intercepts by type, finally always runs
The first matching catch clause (by instanceof order) handles the exception; the finally runs on every exit, including returns and throws. Catch clauses test top to bottom, so specific types come before broad ones or the compiler refuses the dead block. Return from finally only in books about mistakes, and remember System.exit skips it entirely.
Interview angles
Walk through control flow when an exception is thrown inside a try.+
The try exits immediately; catch clauses are tested top to bottom for the first match; the matching clause runs; finally runs as the construct exits; execution continues after it.
An unmatched exception skips every catch and fails at that level, but finally still runs on the way out. This is why cleanup belongs there (or in try-with-resources): the exit route does not matter to finally.
try { throw new IllegalStateException("boom"); } catch (IllegalStateException e) { /* matched: runs first */ } finally { /* runs second, always */ }
Common misconception: That finally runs 'at the end of the try'. It runs at the end of the construct, after the catch when one matched.
Follow-up: Which two mechanisms skip finally entirely?
Why must catch clauses be ordered most-specific-first?+
Because matching is top to bottom; a broader clause above a narrower one makes the narrow clause unreachable, and the compiler refuses it with 'exception X has already been caught'.
The rule converts a classic silent bug (handler that never fires) into a compile error. The same logic drives multi-catch: related alternatives cannot coexist with an ancestor that already matches them.
catch (FileNotFoundException e) { ... } // must come first catch (IOException e) { ... } // broader: catches the rest
Common misconception: That the compiler picks the best-matching clause regardless of order, like overload resolution. It does not; first match wins, full stop.
Follow-up: What error appears when the two clauses above are swapped?
What are the sharp edges of finally?+
A return or throw inside finally overwrites whatever the try was doing, silently discarding exceptions or return values; System.exit skips finally because the JVM stops.
Both verified in this lesson: a method with return 1 in try and return 2 in finally returns 2, and a try whose finally prints after System.exit(0) prints nothing. Cleanup belongs in finally; flow decisions do not.
try { return 1; } finally { return 2; } // returns 2: the try's return is discarded
Common misconception: That finally is 'mostly harmless'. A throw in finally can replace a diagnostic exception with a misleading one, which is why cleanup there should be cautious.
Follow-up: What should replace a finally block that only closes resources?
When is a catch block itself a compile error?+
When it can never match: a duplicate or superclass-covered type (already caught), or a checked type no statement in the try can throw.
The first case is ordering; the second is coverage. Together they make the try/catch construct statically checked from both directions, in the same spirit as reachability rules for return statements.
try { riskyIO(); } // throws IOException only catch (SQLException e) { } // error: exception SQLException is never thrown in body
Common misconception: That extra catch clauses are harmless future-proofing. The compiler treats unreachable ones as errors, and rightly: they hide misunderstandings.
Follow-up: How do you write a catch for a type that a future refactor might start throwing?
What is the difference between throw and throws?+
throw raises an exception instance at runtime; throws is a declaration listing the checked exceptions a method may let escape to its caller.
Unchecked exceptions can also be thrown through without a throws clause, but declaring them documents the contract (some teams do it for clarity). The declaration belongs in the method signature because the caller's obligation starts there.
static String read(String path) throws IOException { // declaration throw new IOException("missing"); // raising }
Common misconception: That throws is part of the method body's behaviour switch. It is API documentation the compiler enforces, and it is worth keeping honest.
Follow-up: What does an empty throws list communicate in a refactor review?