在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