0

What actually happens inside the VM when a value is returned from finally?

Here is an example: code of the static method in Java and its bytecode.

public static int test() {
    try {
        throw new Exception();
    } catch (Exception e) {
        return 1234;
    } finally {
        return 5678;
    }
}

Why are there 3 more instructions (lines 17, 18, 21) after the ireturn instruction (line 16), which should return 5678, which "will be popped from the operand stack and pushed onto the operand stack of the frame of the invoker"?

public static int test();
    descriptor: ()I
    flags: (0x0009) ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=3, args_size=0
         0: new           #7                  // class java/lang/Exception
         3: dup
         4: invokespecial #9                  // Method java/lang/Exception."<init>":()V
         7: athrow
         8: astore_0
         9: sipush        1234
        12: istore_1
        13: sipush        5678
        16: ireturn
        17: astore_2
        18: sipush        5678
        21: ireturn
      Exception table:
         from    to  target type
             0     8     8   Class java/lang/Exception
             0    13    17   any
      LineNumberTable:
        line 9: 0
        line 10: 8
        line 11: 9
        line 13: 13
      StackMapTable: number_of_entries = 2
        frame_type = 72 /* same_locals_1_stack_item */
          stack = [ class java/lang/Exception ]
        frame_type = 72 /* same_locals_1_stack_item */
          stack = [ class java/lang/Throwable ]
  • In modern Java, code in a finally block is duplicated and inlined everywhere appropriate, which is why you see multiple copies of the finally block code here. – Antimony Apr 25 '21 at 21:23
  • 1
    A smart compiler could simplify the generated code, but Java compilers usually don’t try. Optimizations are done by JIT compiler. It [had been even worse with javac](https://stackoverflow.com/q/25615417/2711488) in the past. However, returning from finally (or any other control flow swallowing exceptions) is not recommended and rare in practice, so it’s even less worth trying to identify and optimize such scenarios. – Holger Apr 26 '21 at 09:12

0 Answers0