public class Test
{
public static void main(String[] args)
{
System.out.println(new Test().test());
}static int test()
{
int x = 1;
try
{
return x;
}
finally
{
++x;
}
}
}
2 回答

繁星coding
TA贡献1797条经验 获得超4个赞
写了个简单的类
static int test() { int x=5; try { return x; } finally { x=10; } }
编译后的字节码为
这里说一下,对于try catch finally的编译,编译器会把finally里的代码附在每一个分支的后面
static int test();
0 iconst_5
1 istore_0 [x] //存在局部变量表0位置
2 iload_0 [x] //读取0位置到操作数栈
//下边是finally代码块,附在成功分支后面
istore_2 //另存在2位置 bipush 10 //10放入操作数栈 istore_0 [x] //存在0位置,所以,这时候0位置的变量为10 iload_2 //读取2号位置,这时是5 ireturn //返回5
//下面是异常分子处理
9 astore_1
10 bipush 10
12 istore_0 [x]
13 aload_1
14 athrow

守着一只汪
TA贡献1872条经验 获得超3个赞
因为在运行到return时,该返回值/地址就已经被记录
所以finally里的改变不会起作用
但假如返回值为引用类型,finally块是可以改变其内容的
如下例子~ 想想会返回什么
public class Test { public static void main(String[] args) { System.out.println(new Test().test().toString()); }static StringBuffer test() { StringBuffer x = new StringBuffer("hi"); try { return x; } finally { x.append("hello"); } } }
添加回答
举报
0/150
提交
取消