当一个值从 finally 返回时,VM 内部实际发生了什么?

问题描述

当从 finally 返回一个值时,VM 内部究竟发生了什么?

这里是一个例子:Java中静态方法代码及其字节码。

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

为什么在 ireturn 指令(第 16 行)之后还有 3 条指令(第 17、18、21 行),它们应该返回 5678,它“将从操作数堆栈中弹出并压入调用者”?

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 ]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)