java異常處理:finally中不要return

來源:互聯網
上載者:User

 

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就是用來釋放資源的!!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.