在finally塊中使用try catch,並且catch的時候拋出異常的一個問題


在finally中使用try/catch,並且catch的時候拋出異常

 

IDEA會提示警告

Reports throw statements inside of finally blocks. While occasionally intended, such throw statements may mask exceptions thrown, and tremendously complicate debugging.

大意是:這樣可能會掩蓋異常拋出

 

做以下測試代碼: 

public static void main(String[] args) throws Exception {
    try{
        throw new Exception("異常1");
    }catch (Exception e){
        throw new Exception("異常2");
    }finally {
        try {
            throw new Exception("異常3");
        } catch (Exception e) {
            throw new Exception("異常4");
        }
    }
}

  

輸出結果為:

Exception in thread "main" java.lang.Exception: 異常4
  at cn.com.dataocean.cip.web.Test.main(Test.java:22)

只拋出了一個異常4,並沒有拋出異常2。所以以后不可以在finally塊中的catch中拋出異常了。

 

原創文章,歡迎轉載,轉載請注明出處!

 


免責聲明!

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



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