在finally中使用try/catch,并且catch的时候抛出异常

在finally块中使用try catch,并且catch的时候抛出异常的一个问题

 

IDEA会提示警告

在finally块中使用try catch,并且catch的时候抛出异常的一个问题

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

 

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

 

相关文章:

  • 2021-12-16
  • 2021-11-11
  • 2021-09-27
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
猜你喜欢
  • 2021-10-06
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2021-08-21
相关资源
相似解决方案