下面这段代码的执行结果是怎样的呢?
publc int test(){ int x; try{ x = 1; return x; }catch(Exception e){ x = 2; return x; }finally{ x = 3; } }
相信对Java比较熟悉的朋友马上会说出正确答案:正常返回1,异常返回2。我第一次看到这段代码时,对于finally里面的x=3产生了疑惑,不确定最后返回的x是否变成了3,直到从《深入理解Java虚拟机》里面找到了这段代码的字节码,才明白其运行机制。下面是上面这段Java代码的字节码:
public int test(); Code: Stack=1, Locals=5, Args_size=1 0: iconst_1 //将1写入栈顶 1: istore_1 //将栈顶值(1)写入第2个int型本地变量 2: iload_1 //将第2个int型本地变量load到栈顶(Return语句的开始) 3: istore 4 //保存栈顶值到第4个int型本地变量,此时x=1 5: iconst_3 //将3写入栈顶(Finally开始) 6: istore_1 //将3写入第2个int型本地变量 7: iload 4 //将第4个int型本地变量的值laod到栈顶 9: ireturn //返回栈顶的值 10: astore_2 11: iconst_2 12: istore_1 13: iload_1 14: istore 4 16: iconst_3 17: istore_1 18: iload 4 20: ireturn 21: astore_3 22: iconst_3 23: istore_1 24: aload_3 25: athrow从上面的字节码可以看出,Return语句被分为两部分:istore 4和iload 4&ireturn,在store和load之间插入的是finally代码,x的值首先被存放到一个指定的位置,再执行finally语句,这时finally中的代码已无法影响返回值了。