1. 程式人生 > >在try-catch-finally語句中,return和finally的關係

在try-catch-finally語句中,return和finally的關係

public class TestTryCatch { public static void main(String[] args) { TestTryCatch test = new TestTryCatch(); int fun = test.fun(); System.out.println(fun); } public int fun() { int i = 10; try { //doing something return i; }catch(Exception e){ return i; }finally{ i = 20; } } }

控制檯輸出:10

debug除錯結果:先執行return i;然後執行finally語句,最後回到return i語句,但是finally語句不會改變返回值

結論:無論finally語句塊中執行了什麼操作,都無法影響返回值,所以試圖在finally語句塊中修改返回值是徒勞的。因此,finally語句塊設計出來的目的只是為了讓方法執行一些重要的收尾工作,而不是用來計算返回值的。