finally中不要使用return的兩種情況


以下兩種情況要避免在finally中使用return

1. 如果catch塊中捕獲了異常,並將該異常throw給上級調用者處理,但finally中return了,那么catch塊中的throw就失效了,上級方法調用者是捕獲不到異常的

   例: 如下代碼上級調用者是捕獲不到異常的

public static void main(String[] args){
        try {
            System.out.println(work());
        }catch (Exception e){
            //捕獲不到異常
            e.printStackTrace();
        }
    }


    public static int work(){
        int c = 0;
        try{
            c = 3/0;
        }catch (Exception e){
            //除以0 ,會有異常:ArithmeticException: / by zero
            throw e;
        } finally {
            return c;
        }
    }

 

2 . 在finally里的return之前執行了其他return ,最終的返回值還是finally中的return

例 : 如下代碼返回的是finally里return的5

public static void main(String[] args){
        System.out.println(work());
    }


    public static int work(){
        int x =3;
        try{
            return x;
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            x = 5;
            return x;
        }
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM