Java異常處理中finally中的return會覆蓋catch語句中的return語句


Java異常處理中finally中的return會覆蓋catch語句中的return語句和throw語句,所以Java不建議在finally中使用return語句

此外 finally中的throw語句也會覆蓋catch語句中的return語句和throw語句

程序實例如下:(本代碼來源於CSDN某大神:http://blog.csdn.net/hguisu/article/details/6155636   在此表示感謝)

package Test;  
  
public class TestException {  
    public TestException() {  
    }  
  
    boolean testEx() throws Exception {  
        boolean ret = true;  
        try {  
            ret = testEx1();  
        } catch (Exception e) {  
            System.out.println("testEx, catch exception");  
            ret = false;  
            throw e;  
        } finally {  
            System.out.println("testEx, finally; return value=" + ret);  
            return ret;  
        }  
    }  
  
    boolean testEx1() throws Exception {  
        boolean ret = true;  
        try {  
            ret = testEx2();  
            if (!ret) {  
                return false;  
            }  
            System.out.println("testEx1, at the end of try");  
            return ret;  
        } catch (Exception e) {  
            System.out.println("testEx1, catch exception");  
            ret = false;  
            throw e;  
        } finally {  
            System.out.println("testEx1, finally; return value=" + ret);  
            return ret;  
        }  
    }  
  
    boolean testEx2() throws Exception {  
        boolean ret = true;  
        try {  
            int b = 12;  
            int c;  
            for (int i = 2; i >= -2; i--) {  
                c = b / i;  
                System.out.println("i=" + i);  
            }  
            return true;  
        } catch (Exception e) {  
            System.out.println("testEx2, catch exception");  
           ret = false;  
            throw e;  
        } finally {  
            System.out.println("testEx2, finally; return value=" + ret);  
            return ret;  
        }  
    }  
      public static void main(String[] args) {  
        TestException testException1 = new TestException();  
        try {  
            testException1.testEx();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  

輸出結果為:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

 

 

 

此外:

finally塊的語句在try或catch中的return語句執行之后返回之前執行且finally里的修改語句不能影響try或catch中 return已經確定的返回值(如果catch語句中返回的是一個引用,那么在finally語句中對引用的內容進行修改是會影響catch中return的返回值的,若finally里也有return語句則覆蓋try或catch中的return語句直接返回。

 


免責聲明!

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



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