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條經(jīng)驗 獲得超4個贊
寫了個簡單的類
static?int?test() { int?x=5; try { return?x; } finally { x=10; } }
編譯后的字節(jié)碼為
這里說一下,對于try catch finally的編譯,編譯器會把finally里的代碼附在每一個分支的后面
static int test();
0 iconst_5
1 istore_0 [x] //存在局部變量表0位置
2 iload_0 [x] //讀取0位置到操作數(shù)棧
//下邊是finally代碼塊,附在成功分支后面
??istore_2??????//另存在2位置 ??bipush?10?????//10放入操作數(shù)棧 ??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條經(jīng)驗 獲得超4個贊
因為在運行到return時,該返回值/地址就已經(jīng)被記錄
所以finally里的改變不會起作用
但假如返回值為引用類型,finally塊是可以改變其內(nèi)容的
如下例子~ 想想會返回什么
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
提交
取消