try catch finally 用法
阿新 • • 發佈:2018-12-15
在講之前我們先看一段程式:
public class Test { public static void main(String[] args) { System.out.println("return value of getValue(): " + getValue()); } public static int getValue() { try { return 0; } finally { return 1; } } }
請問答案是:“return value of getValue():0 還是 return value of getValue():1”呢?
在分析此問題之前先看看它們的介紹:
try catch finally 是java中的異常處理的常用識別符號,常用的組合為:
1. try { //邏輯程式碼 }catch(exception e){ //異常處理程式碼 } finally{ //一定要執行的程式碼 } 2. try { //邏輯程式碼 }catch(exception e){ //異常處理程式碼 } 3. try{ //邏輯程式碼 }finally{ //一定要執行的程式碼 }
try { //執行的程式碼,其中可能有異常。一旦發現異常,則立即跳到catch執行。否則不會執行catch裡面的內容 } catch { //除非try裡面執行程式碼發生了異常,否則這裡的程式碼不會執行 } finally { //不管什麼情況都會執行,包括try catch 裡面用了return ,可以理解為只要執行了try或者catch,就一定會執行 finally }
其實這些都還好理解,主要就是finally中的程式碼執行順序的問題,這裡給出我的想法:
正常情況下,先執行try裡面的程式碼,捕獲到異常後執行catch中的程式碼,最後執行finally中程式碼,但當在try catch中執行到return時,要判斷finally中的程式碼是否執行,如果沒有,應先執行finally中程式碼再返回。
例如某些操作,如關閉資料庫等。
為了證實我的猜想,我們來看幾個例子:
程式碼1:
public class Test {
public static void main(String[] args) {
System.out.println("return value of getValue(): " +
getValue());
}
public static int getValue() {
try {
System.out.println("try...");
throw new Exception();
} catch(Exception e){
System.out.println("catch...");
return 0;
}finally {
System.out.println("finally...");
return 1;
}
}
}
執行結果:
try...
catch...
finally...
return value of getValue(): 1
程式碼2:(將return 1 註釋)
public class Test {
public static void main(String[] args) {
System.out.println("return value of getValue(): " +
getValue());
}
public static int getValue() {
try {
System.out.println("try...");
throw new Exception();
} catch(Exception e){
System.out.println("catch...");
return 0;
}finally {
System.out.println("finally...");
//return 1;
}
}
}
執行結果:
try...
catch...
finally...
return value of getValue(): 0
意思就是在try 和catch中如果要return,會先去執行finally中的內容再返回。
講到這裡,前面題目的答案也就知道了,是“return value of getValue():1”。
當在try中要return的時候,判斷是否有finally程式碼,如果有,先執行finally,所以直接return 1.