Video in progress

Strong Junior ⚙️ JVM and memory

What does try/finally look like in bytecode, and why is a return inside finally dangerous?

static int f() {
    try {
        throw new IllegalStateException("xato");
    } finally {
        return 42;
    }
}

javac copies the finally block onto every exit path (a normal return and an exception) and adds an "any exception" entry to the exception table. If finally contains a return, it silently swallows both the value from the try and any exception that was thrown.

📖 Answer

There is no separate finally instruction in bytecode. Look at it with javap -c and you will see the finally code duplicated in several places:

  • on the path where the try ended normally;
  • inside the any handler in the exception table. It catches the exception, runs the finally code and rethrows with athrow.
Exception table:
   from    to  target type
     0     10    13   any

Now the code above. The exception is thrown, control goes to the any handler, the finally code runs, and there it hits return 42. We never reach the rethrow instruction. The result: f() returns 42, and the IllegalStateException vanishes without a trace. Nothing in the log.

In the same way, a return in finally also replaces the value of a return in the try. javac warns about this with -Xlint:finally.

The rule is simple: finally is only for cleanup. Even better is try-with-resources. It also turns into much longer bytecode (an exception thrown on close is kept through addSuppressed), but the compiler writes it correctly for you.