java異常處理:finally中不要return
阿新 • • 發佈:2019-01-10
參考牛人部落格:http://www.cnblogs.com/Fskjb/archive/2012/02/15/2353256.html
public class Ex1 {public static void main(String[] args) {
System.out.println(Ex1.getResult());
}
public static int getResult(){
int a =100;
try{
return a+10; //注意,java的基礎資料型別是值傳遞,這裡的返回值已經和上面的a沒有關係了
}finally{
return a; //最後再把值重定向到a(相當於將try中的返回值覆蓋掉),所以輸出還是100 }
}
}
再看一個例子:
public class Ex1 {public static void main(String[] args) {
try{
System.out.println(Ex1.getResult());
}catch
e.printStackTrace();
System.out.println("截獲異常catch");
}finally{
System.out.println("異常處理finally");
}
}
public static int getResult() throws Exception{
int a =100;
try{
a=a+10;
throw
}catch(Exception e){
System.out.println("截獲異常並重新丟擲異常");
throw new Exception();
}finally{
return a;
}
}
}
輸出如下:
截獲異常並重新丟擲異常
110
異常處理finally
關鍵的“截獲異常catch”卻沒有執行!!!
原因是在getResult()的finally中return一個值,等同於告訴編譯器該方法沒有異常,但實際上異常是有的,這樣的結果是該方法的呼叫者卻捕獲不到異常,相對於異常被無端的被吃掉了,隱藏殺機啊!!
結論:不要再finally中試圖return一個值,這樣可能會導致一些意想不到的邏輯錯誤,finally就是用來釋放資源的!!