1. 程式人生 > >java異常處理:finally中不要return

java異常處理:finally中不要return

參考牛人部落格: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沒有關係了
        }catch(Exception e){             e.printStackTrace();  
        }finally{
            return a;    //最後再把值重定向到a(相當於將try中的返回值覆蓋掉),所以輸出還是100        }
    }
} 複製程式碼

 再看一個例子:

複製程式碼 public class Ex1 {

    public static void main(String[] args) {
        try{
        System.out.println(Ex1.getResult());
        }catch
(Exception e){
            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
 new RuntimeException();
        }catch(Exception e){
            System.out.println("截獲異常並重新丟擲異常");
            throw new Exception();            
        }finally{
            return a;
        }
    }
} 複製程式碼

輸出如下:

截獲異常並重新丟擲異常
110
異常處理finally
關鍵的“截獲異常catch”卻沒有執行!!!

原因是在getResult()的finally中return一個值,等同於告訴編譯器該方法沒有異常,但實際上異常是有的,這樣的結果是該方法的呼叫者卻捕獲不到異常,相對於異常被無端的被吃掉了,隱藏殺機啊!!

結論:不要再finally中試圖return一個值,這樣可能會導致一些意想不到的邏輯錯誤,finally就是用來釋放資源的!!