java 中try catch finally 的具體執行順序返回結果+程式碼測試
阿新 • • 發佈:2019-01-08
執行順序的重點就在finally中,具體如下:
(1)、try:它裡面放置可能引發異常的程式碼
(2)、catch:後面對應異常型別和一個程式碼塊,用於表明該catch塊用於處理這種型別的程式碼塊,可以有多個catch塊。
(3)、finally:主要用於回收在try塊裡開啟的物力資源(如資料庫連線、網路連線和磁碟檔案),異常機制總是保證
finally塊總是被執行。只有finally塊,執行完成之後,才會回來執行try或者catch塊中的return或者throw語句,如果
finally中使用了return或者throw等終止方法的語句,則就不會跳回執行,直接停止。
為了 證明上面的結論是正確的,做了如下測試:
class Lxk { private static int testFinallyFunc() { String s = null; int result; try { s.equals("ss"); result = 1; //不走 System.out.println("try " + result); //不走 } catch (Exception e) { result = 2; System.out.println("catch " + result); //走,且會給result賦值 return result; //不一定會return } finally { result = 3; System.out.println("finally " + result); //return result; //這個開啟返回的就是finally中的結果 3;關閉返回的就是catch中的結果 2 } return result; //這個就佔個位置,開啟finally的return這個返回就永遠走不到了,得註釋了。 } public static void main(String[] a) throws Exception { int returnResult = testFinallyFunc(); System.out.println("get return result " + returnResult); } }
finally中有return語句的時候的結果如下:
catch 2
finally 3
get return result 3
finally中沒有return語句的時候的結果如下:
catch 2
finally 3
get return result 2
結論:
try catch finally 都有返回:最終都會得到finally的返回結果。
try catch 都有返回 finally沒有返回:try出現異常,會得到catch的返回結果。finally中的操作,不影響返回結果。
try catch 都有返回 finally沒有返回:try沒有異常,會得到try的返回結果。 finally中的操作,不影響返回結果。
有了上面的這個理論,之後,看下面的這個程式的返回結果,應該是多少。
private static int testFunc2() {
int x = 1;
try {
return x;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
++x;
}
return x;
}