[java]从字节码看finally块与return执行顺序

java代码:
public int getI() {
    int i = 1;
    try {
        return i;
    } finally {
        i++;
    }
}
字节码(javap -c -l YourClass.class):
public int getI();
    Code:
       0: iconst_1
       1: istore_1
       2: iload_1
       3: istore_3
       4: iinc          1, 1
       7: iload_3
       8: ireturn
       9: astore_2
      10: iinc          1, 1
      13: aload_2
      14: athrow
    Exception table:
       from    to  target type
           2     4     9   any
解释:
0: iconst_1              int型常量1进栈
1: istore_1               将栈顶int存入局部变量表位置1(位置0为this)
2: iload_1                int型局部变量(位置1)进栈
3: istore_3              将栈顶int存入局部变量表位置3
4: iinc          1, 1      局部变量表位置1自增1(finally块i++)
7: iload_3               int型局部变量(位置3)进栈

8: ireturn                返回当前操作数栈中的1


finally块会在return之前执行。

【待补充】为什么getI()返回值是1而不是2

你可能感兴趣的:(问题记录,JAVA)