What javac does
finally
No instruction for it: the finally block is copied onto every exit.
The JVM has no instruction for finally. javac copies the finally block onto every way out of the try: before each return, and into a handler that catches anything, runs the block and rethrows.
The source
// finally: the block's code is copied onto every way out of the try.
public class Finally {
static int count;
static int work(int x) {
try {
if (x < 0) {
return -1;
}
return x * 2;
} finally {
count++;
}
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
count++appears three times: beforereturn -1, beforereturn x * 2, and in the handler.- The return value is stored in a local (
istore_1) before the finally code runs and loaded again after it, so the finally block cannot change a value that has already been computed for return. - The exception table's
anyentries cover the try's code but not the copies of the finally block. - Old compilers kept one copy of the block and reached it with
jsrandret. Class files since Java 7 may not use them.
Finally.class
static int work(int x)
javac --release 8 to 25 (the same bytecode for every release)
| From | To | Handler | Catches |
|---|---|---|---|
| 0 | 6 | 30 | anything (any) |
| 16 | 20 | 30 | anything (any) |