How does javac compile Java's try, catch, finally and try-with-resources to bytecode, and what does the exception table do?
answer
- nothing runs on entering try
- from, to, target, type
- first matching row wins
- one finally copy per way out
- two Throwable rows around close
basics
~20 sjavac emits a try body as ordinary instructions and records handlers in the method's exception table, searched only on a throw. It copies finally onto every exit and expands try-with-resources into a normal-exit close plus a handler that closes and rethrows.
solid answer
~40 s`javac` emits a try body as ordinary bytecode with no entry instruction, and records each handler in the method's exception table as a row of `from`, `to`, `target` and `type`. When something throws, the JVM searches those rows in table order, and the first row covering the throwing instruction with a matching class wins. The path that does not throw pays at most a `goto` over the handlers and any `finally` copy. Since class-file version 51.0 rules out `jsr`, `javac` 27 copies the `finally` body onto each `return`, `break`, `continue` and normal exit, and adds an `any` handler that runs another copy and rethrows with `athrow`. Try-with-resources is lowered first: `close()` on normal exit, plus a `catch (Throwable)` that closes the resource, records a close failure with `addSuppressed` and rethrows.
code
java · 21 linespublic class TryShape {
void work() { }
void handle(Exception e) { }
void cleanup() { }
int compute(int x) {
try {
work();
return x;
} catch (IllegalStateException e) {
handle(e);
return -1;
} finally {
cleanup();
}
}
public static void main(String[] args) {
System.out.println(new TryShape().compute(7)); // 7
}
}go deeper
Recall that catch blocks are found through a table in the compiled method, not through instructions run on entry, and that finally runs on every way out of the try.
Explain the four columns of the exception table, why the search order gives first match wins, and how to read those rows in javap -c output for a small method.
Trace finally copies, the any handler and the range gaps in a real listing, and reason about what a try costs: no entry instruction, but more bytes that count against C2's inlining limits.
Use this to settle arguments with evidence: challenge folklore that try blocks are slow, ask for a profile before hot code is restructured, and weigh large finally bodies against method size limits.
## The exception table A compiled method's `Code` attribute holds its bytecode and, beside it, an `exception_table`. Each row has four items: - `start_pc` and `end_pc` give the half-open bytecode range `[start_pc, end_pc)` where the handler is active. - `handler_pc` says where the handler's code starts. - `catch_type` names a class, or is zero, which matches every exception and is what implements `finally`. `javap -c` prints these as `from`, `to`, `target` and `type`, showing zero as `any`. When something throws, the table is used like this: 1. The JVM takes the offset of the instruction that threw, and the exception's class. 2. It searches the current method's rows from the top of the table. The first row whose range holds the offset, and whose class is the exception's class or a superclass, matches. 3. On a match, the operand stack is cleared, the exception is pushed, and execution continues at `handler_pc`. 4. With no match, the frame is popped and the search repeats in the caller. The JVM does not enforce nesting or ordering of rows. The subtype-before-supertype rule belongs to the Java language: JLS 11.2.3 makes the reverse order a compile-time error, which `javac` reports as `exception {0} has already been caught`. `javac` also writes a try statement's catch rows in source order, so first match gives Java's catch-order semantics. ## What `try` and `catch` compile to The JVMS's non-normative compiling chapter says that with no exception a `try` block "behaves as though the try were not there". `work(); after();` compiles to five instructions. Wrapping `work()` in a `try` with one `catch` kept those five and added a `goto` followed by the handler's code. So the path that does not throw pays: - **No entry instruction.** Nothing is pushed or registered on the way in. - **A jump, where one is needed.** The `goto` skips the handler. - **Bytes.** Handlers enlarge the method. `code_length` must stay below 65536, and C2's `MaxInlineSize` and `FreqInlineSize` are limits on bytecode size, so a larger method can lose inlining. "No cost" is therefore right about entering a `try` and too strong about the whole statement. ## How `finally` is copied JVMS section 3.13 still explains `finally` with `jsr` and `ret`, but it opens by assuming class-file version 50.0 or below. From version 51.0, which is Java SE 7, those instructions must not appear. `javac` 27 writes version 71 and copies the `finally` body onto each exit instead. For the `compute` method in the code example, `javap -c -p` prints: ```text 0: aload_0 1: invokevirtual #7 // Method work:()V 4: iload_1 5: istore_2 6: aload_0 7: invokevirtual #12 // Method cleanup:()V 10: iload_2 11: ireturn 12: astore_2 13: aload_0 14: aload_2 15: invokevirtual #17 // Method handle:(Ljava/lang/Exception;)V 18: iconst_m1 19: istore_3 20: aload_0 21: invokevirtual #12 // Method cleanup:()V 24: iload_3 25: ireturn 26: astore 4 28: aload_0 29: invokevirtual #12 // Method cleanup:()V 32: aload 4 34: athrow Exception table: from to target type 0 6 12 Class java/lang/IllegalStateException 0 6 26 any 12 20 26 any 26 28 26 any ``` - **Three copies of `cleanup()`.** At 6 for the `return` in the `try`, at 20 for the `return` in the `catch`, and at 28 in the `any` handler. `break` and `continue` get copies as well. - **The return value is saved first.** `istore_2` keeps it in a temporary, the copy runs, and `iload_2` reloads it, so a `finally` that assigns the local cannot change what is returned. A `return` inside `finally` is a different matter: it overrides the result. - **The `any` handler rethrows.** It stores the exception, runs a copy, reloads the exception and executes `athrow`. - **The `any` ranges have gaps.** Offsets 6 to 12 and 20 to 26 are not covered, so an exception from one of those copies does not run `finally` a second time. The `catch` body at 12 to 20 is covered, so a throw from the `catch` still runs it. The last row covers only the handler's own `astore`. ## What try-with-resources expands into JLS 14.20.3.1 gives the statement's meaning as a translation to `try`, `catch` and `finally`, and `javac`'s internal `Lower.makeTwrTry` builds a slimmer shape: | Aspect | JLS translation | `javac` 27 | |---|---|---| | Primary exception | A `#primaryExc` local, set in a `catch` | The `catch (Throwable)` parameter itself | | Normal-path `close()` | In `finally`, when `#primaryExc` is null | Copied after the body, on each normal exit | | Failure-path `close()` | In `finally`, wrapped in `try` and `catch` | In the `catch (Throwable)`, wrapped the same way | | Null check | Always | Omitted when the initialiser is a `new` expression | Compiled, `try (Res r = make()) { r.use(); }` shows `ifnull` guards and two `Class java/lang/Throwable` rows: - The normal-path `close()` sits outside the first row's range, so its failure propagates as the primary exception. - The second row covers the failure-path `close()`. Its handler calls `addSuppressed` on the primary exception and falls through to `athrow`. - Several resources nest, one level per resource. A `catch` or `finally` on the statement wraps all of it in an outer `try`, so that `catch` can catch the resources' failures and that `finally` runs after they are closed. For the methods above, `javac` 25 prints the same `javap -c` listing as `javac` 27, and `Gen.genTry` and `Lower.makeTwrTry` are unchanged between the two tags.
- Would the JVM run a class file whose exception table lists a supertype row above a subtype row?Yes. The JVM does not enforce nesting or ordering of rows; it takes the first match. A class generated with a `RuntimeException` row above an `IllegalStateException` row over the same range loads and runs on JDK 27, and the supertype row's handler takes the exception, leaving the other row dead. Rejecting that order is the Java language's rule, JLS 11.2.3, which a compiler enforces.
- Why can a finally block's assignment to a returned local not change the returned value?`javac` evaluates the return expression first and saves it in a temporary local, then runs the inlined `finally` copy, then reloads the temporary and returns. For `int x = 1; try { return x; } finally { x = 2; }` the listing is `iload_1, istore_2`, then `iconst_2, istore_1`, then `iload_2, ireturn`, so the method returns 1. Mutating a returned object still shows, because only the reference was saved.
- Does adding a try/catch around a hot call slow down the path that does not throw?At bytecode level it adds no entry instruction and at most a `goto` over the handler. One indirect effect is size: handlers and `finally` copies add bytes, and C2's `MaxInlineSize` and `FreqInlineSize` limit inlining by bytecode size, so a bigger method can lose inlining. Profile the hot path before restructuring it, because the bytecode alone does not give a timing.
- Entering a try block runs an instruction that registers its handlers.
- javac compiles finally to one shared subroutine called with jsr.
- The JVM refuses to run a class whose exception table lists a supertype first.
- A try statement adds nothing to a method's bytecode unless something throws.
- javac emits the JLS try-with-resources translation literally, including its #primaryExc local.
- An any row covers the inlined finally copies, so a failing finally runs again.
- try-with-resources statement
- Java 1.7
- Class files without jsr and ret (version 51.0)
- Java 1.7
- Throwable.addSuppressed
- Java 1.7
Assumes javac 27 at class-file version 71; javac 25 prints the same listings, and jsr has been barred since class-file version 51.0.
context
- Chapter 4. The class File Formatdocs.oracle.com
- Chapter 14. Blocks, Statements, and Patternsdocs.oracle.com
- Gen.java at jdk-27-gagithub.com