HexplainedJavaThread dumps soonHeap dumps soonAbout
ViewerFormatWhat javac doesOpcodesConstantsAttributesVersionsJAR
Java class files › What javac does › finally

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: before return -1, before return 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 any entries 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 jsr and ret. 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)

7if (x < 0) {
0iload_0 // x
1ifge 16
8return -1;
4iconst_m1
5istore_1
12count++;
6getstatic #7// Finally.count : int
9iconst_1
10iadd
11putstatic #7// Finally.count : int
8return -1;
14iload_1
15ireturn
10return x * 2;
16iload_0 // x
17iconst_2
18imul
19istore_1
12count++;
20getstatic #7// Finally.count : int
23iconst_1
24iadd
25putstatic #7// Finally.count : int
10return x * 2;
28iload_1
29ireturn
12count++;
30astore_2 catch any, any
31getstatic #7// Finally.count : int
34iconst_1
35iadd
36putstatic #7// Finally.count : int
13}
39aload_2
40athrow
FromToHandlerCatches
0630anything (any)
162030anything (any)

Open in the viewer

← try-with-resourcesAll topicssynchronized →

By the author of this site

Reading bytecode is half the story; running it is the other half. You execute exactly this kind of code in Build a JVM in Rust: Class files, an interpreter, objects and invokedynamic from scratch, on the real JDK class library.

Read Chapter 1 free

Java and the JVM are trademarks of Oracle; this site is not affiliated with Oracle. Field names follow the Java Virtual Machine Specification; the explanations are our own.

Sister sites: What's in my DB · LLM Anatomy · Distribution Atlas · Notation Decoder · uresk.net

Made by Spencer Uresk · About · Files you open stay on your device.