在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中抛出异常了。

原创文章,欢迎转载,转载请注明出处!

原文地址:https://www.cnblogs.com/acm-bingzi/p/finallyCatch.html