The idea: a throw leaves frames until a catch matches

Every method call pushes a frame on the thread's call stack, and a normal return pops it. A throw is a third way to leave code. The exception object is made, and the JVM looks for a handler: first in the method that threw, then in its caller, then in the caller's caller. Each method that has no matching handler ends at once and its frame is popped. This is called stack unwinding. On the way out, every finally block that the exception passes through still runs.

Three frames, main at the bottom, a in the middle, b on top. b throws FileNotFoundException at line 23. b has no handler: its frame is popped. In a, catch IllegalArgumentException does not match, the finally block prints a finally, then a's frame is popped. In main, catch IOException matches because FileNotFoundException is a subclass of IOException
The exception goes down the stack, one frame at a time, until a catch of its type or a supertype is found.

How to read the page

  • Source: the Java program with its line numbers. Yellow is the line that runs, blue is a catch being tested, red is where an exception is thrown or arrives.
  • Call stack: one box per frame, main at the bottom. Each frame shows its current line, its locals and a pending completion while a finally runs. A red box is an exception in flight, orange is a caught exception bound to e, blue is a return value on its way to the caller.
  • Console: what System.out printed, and in red what System.err printed. The exit status shows at the end.

The page's programs were compiled and run with a real JDK; the console shows the same lines.

How a catch is chosen

A try block marks a range of lines. When an exception comes out of that range, the catch clauses are tested in order, top to bottom. The first one whose type is the exception's class, or a superclass of it, runs. The rest are skipped.

Line 23 of b()Catch in a()Catch in main()Console
throw FileNotFoundExceptionIllegalArgumentException ✗IOException ✓ (a superclass)b runs, a finally, main caught …, main finally
throw IllegalArgumentExceptionIllegalArgumentException ✓not reached b runs, a caught …, a finally, a: after try, main: a returned, main finally
int z = 10 / 0✗✗b runs, a finally, main finally, then the stack trace; exit status 1

Notice that a: after try only prints when a handled the exception itself. When the exception passes through, the rest of a never runs. (Demo: FileNotFoundException, caught two frames up, Demo: IllegalArgumentException, caught in a())

Because the order matters, Java refuses a catch (IOException e) placed before a catch (FileNotFoundException e) in the same try: the second could never run, and the compiler reports it as an error.

finally runs on every way out

A finally block runs when the try is left normally, by return, or by an exception. While it runs, the earlier way out waits. The page shows it as pending in the frame. Two rules follow from this:

  1. The return value is saved first. In f(), return x computes 1 and saves it. The finally block then sets x = 2, but f() still returns 1. The console shows finally: x = 2 and then f() = 1. (Demo: return in try, finally runs first)
  2. A return in finally wins. In g(), the try throws IllegalStateException. The finally block says return 3, which replaces the pending throw. The exception is lost: main's catch never runs and the console shows g() = 3. (Demo: return in finally discards the exception)

A throw inside finally replaces the pending completion in the same way. That is why style guides say: never return or throw from a finally block. javac -Xlint:finally warns about it.

Two timelines. Left, f(): int x = 1; return x saves 1 as pending; finally sets x = 2 and prints finally: x = 2; the pending return 1 goes ahead; main prints f() = 1. Right, g(): throw IllegalStateException is pending; finally runs return 3; the exception is discarded; main prints g() = 3 and its catch never runs
finally runs while the return or throw waits; if finally ends normally the wait ends, if it returns, it replaces it.

Catch, wrap and rethrow

A catch block can throw too. A plain throw e; sends the same object on up the stack. Often a method wraps it instead: load() catches the FileNotFoundException from read() and throws new UncheckedIOException("load failed", e). The old exception becomes the new one's cause, so nothing is lost: main prints cause: java.io.FileNotFoundException: cfg.txt. (Demo: catch, wrap and rethrow)

Checked and unchecked exceptions

Java splits exceptions in two. A checked exception (IOException and its subclasses, and other Exceptions that are not RuntimeExceptions) must be caught or declared with throws. That is why b() and read() say throws IOException. An unchecked exception (RuntimeException and its subclasses, and Error) needs no declaration. This is a compile-time rule only. At run time both kinds unwind the stack in exactly the same way. Wrapping a checked exception in an unchecked one, as load() does, lets it pass through methods that do not declare it.

try-with-resources

try (Res a = new Res("A"); Res b = new Res("B")) { … } closes every resource that was opened, in reverse order, when the block ends, however it ends. The closes run before any catch or finally of the same statement. If the body threw and a close() throws too, the second exception does not replace the first. It is added to the first one's suppressed list (getSuppressed()). The console shows close B, close A, then caught java.io.IOException: body and suppressed: java.lang.IllegalStateException: close B. (Demo: try-with-resources closes B, then A)

An uncaught exception

If no frame catches it, the exception leaves main too. The thread's default uncaught exception handler prints the exception and its stack trace to System.err, and the thread ends. When it is the last non-daemon thread, the JVM exits with status 1. The trace was recorded when the exception was made, so it still names b, a and main with their lines, even though those frames are gone. All the finally blocks on the way ran first. (Demo: 10 / 0 is never caught)

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.b(Main.java:23)
    at Main.a(Main.java:13)
    at Main.main(Main.java:3)

How the JVM finds the handler

The compiler does not insert checks after every call. It writes an exception table for each method: rows of from, to, target and type. When an exception happens at a bytecode offset, the JVM scans the table for the first row whose range holds that offset and whose type matches. If none does, the frame is popped and the scan repeats in the caller at the offset of the call. A finally block is copied onto each normal exit, and an extra row of type any covers the exceptional exit. Running code that does not throw costs nothing extra.

The bytecode javac 21 writes for a(): offset 0 calls b(); the finally code appears three times, at 3, inside the catch block at 14 to 38, and at 41 to 51 ending with athrow. Exception table: from 0 to 3, target 14, type IllegalArgumentException; from 0 to 3, target 41, type any; from 14 to 30, target 41, type any. A FileNotFoundException at offset 0 skips row 1, matches row 2, runs the finally copy at 41 and is thrown again out of a()
javac turns try/catch/finally into table rows; the JVM scans them when an exception happens, not before.

Side note: C++ destructors and RAII

C++ has try, throw and catch but no finally. Instead, during unwinding the destructor of every local object in each popped frame runs, in reverse order of construction. Tying a resource to an object's lifetime is called RAII (resource acquisition is initialization). It plays the role that try-with-resources plays in Java:

void a() {
    std::lock_guard<std::mutex> g(m);   // locks m
    std::ifstream in("data.txt");          // opens the file
    b();                                   // b throws
}   // unwinding: ~ifstream closes the file, then ~lock_guard unlocks m

A destructor must not throw while another exception is unwinding the stack. If it does, C++ calls std::terminate and the program stops. Java's suppressed list is the gentler answer to the same problem. If no handler exists at all, C++ calls std::terminate too, and whether the stack is unwound first is left to the implementation.

See also Recursion to an explicit stack and Heap vs stack in Java for how frames are pushed and popped, Exceptions in the MIPS processor for hardware exceptions and interrupts (a different thing with the same name), and OWASP A10: Mishandling of exceptional conditions for what careless exception handling does to security.

What the page leaves out

The page runs one thread and shows frames as boxes, not the JVM's operand stacks. It leaves out Errors such as StackOverflowError, multi-catch (catch (A | B e)), the precise rethrow rule that lets throw e keep a narrower type, exceptions thrown while a resource is being opened, exception chaining with initCause, Thread.setDefaultUncaughtExceptionHandler, the cost of filling in a stack trace, and how C++ compilers implement zero-cost unwinding with unwind tables (the Itanium ABI). Other languages differ in details: Python has else on try, C# keeps finally but forbids a return in it.

On the mind map

Open the Java & the JVM mind mapJava & the JVMFrom source to bytecode: translate first, or while runningFrom source to bytecodeStartup and class loading: what happens before main()Startup and class loadingJIT compilers: compile hot code using profilesJIT compilersMemory and GC: find and free unreachable objectsMemory and GCCollections: how java.util stores keysCollectionsThreads and memory model: Java threads on real coresThreads and memory modelSpring framework: a container builds your objectsSpring frameworkStack vs heap in JavaStack vs heap in Javaframes on the stack, objects in TLABsException unwindingfinally runs; return in finally winsJava GCsJava GCsParallel, G1 regions, ZGC load barriersTracing vs ref countingTracing vs ref countingrefcount frees at once but leaks cyclesPython GCPython GCrefcount plus a cycle collectorGo GCGo GCtri-colour marking with a write barrierPass by value vs referencePass by value vs referenceJava copies the reference, not the objectParameter passing modesParameter passing modesBy name re-evaluates a[i] at every useCard table and barriersCard table and barriersold-to-young refs marked dirtySafepointsSafepointsall threads park before a pauseOpen the Java & the JVM mind mapJava & the JVMfind and free unreachable objectsMemory and GCStack vs heap in JavaStack vs heap in Javaframes on the stack, objects in TLABsException unwindingfinally runs; return in finally winsJava GCsJava GCsParallel, G1 regions, ZGC load barriersTracing vs ref countingTracing vs ref countingrefcount frees at once but leaks cyclesPython GCPython GCrefcount plus a cycle collectorGo GCGo GCtri-colour marking with a write barrierPass by value vs referencePass by value vs referenceJava copies the reference, not the objectParameter passing modesParameter passing modesBy name re-evaluates a[i] at every useCard table and barriersCard table and barriersold-to-young refs marked dirtySafepointsSafepointsall threads park before a pause
This page on the Java & the JVM mind map · 35 pages in 7 branches · open it to see the whole map and test yourself in recall mode.