程式碼題目
public class TestFinally {
public static void main(String[] args) {
Demo demo = new Demo();
TestFinally tf = new TestFinally();
String result = tf.fun1(demo);
System.out.println(result); // 輸出?
System.out.println(demo.str); // 輸出?
}
private String fun1(Demo demo) {
try {
demo.str += "1";
return fun2(demo); // 返回 fun2 結果
} finally {
demo.str += "2";
}
}
private String fun2(Demo demo) {
try {
demo.str += "3";
return demo.str; // 返回當前 demo.str
} finally {
demo.str += "4";
}
}
}
class Demo { String str = ""; }
執行流程圖解
fun1 執行 demo.str += "1" → str = "1"。
- 呼叫
fun2:demo.str += "3" → str = "13"。
fun2 準備返回 demo.str(值為 "13"),但先執行 finally:demo.str += "4" → str = "134"。
fun2 返回 "13"(返回值在 finally 前已確定)。
fun1 接收返回值 "13",執行自身 finally:demo.str += "2" → str = "1342"。
fun1 返回 "13"。
最終輸出
13
1342
核心結論
- finally 總是在 return 語句執行後、方法實際返回前執行。
- 返回值在
return 語句計算時已確定,finally 中修改變數不影響已確定的返回值(基本類型與物件引用均如此)。
finally 主要用於資源釋放、清理工作,不應依賴它修改返回值。
