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

finally中catch抛出异常
本文探讨了在Java中finally块内的catch语句中抛出异常的行为及其带来的问题。通过示例代码展示,发现此种做法可能导致预期外的异常被掩盖,仅最后一个异常会被输出。因此,在finally块的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值