if(e instanceof XxxException)判断后,throw e 报错提示没有处理其他异常。

今天在项目中碰到这样一个问题,我写了如下代码:

try{
    /**
     * do something
     * 将会 抛出 GeneralSecurityException、IOException
     */
} catch (Exception e) {
    if (e instanceof GeneralSecurityException) {
        throw e;
    }
    logger.info("JSON解析出错。");
}

在try块的业务逻辑中,将会抛出GeneralSecurityException、IOException两个Exception。我在使用了instanceof进行了判断后,使用“throw e”对该异常进行了抛出,结果,提示我没有处理另一个异常——IOException。

然后请教带我的老师,老师让我这么改:

 throw (GeneralSecurityException) e;

然后就没问题了。

我查了一下instanceof关键字的官方定义:

The instanceof operator (§15.20.2). An expression whose type is a reference type may be tested using instanceof to find out whether the class of the object referenced by the run-time value of the expression may be converted to some other reference type.

 也就是说,类型为引用类型的表达式可以使用instanceof进行测试,以找出表达式的运行时值引用的对象类是否可以转换为其他引用类型。

所以,在编译时,即使我们使用了 e instanceof GeneralSecurityException 进行判断,但是当我们使用 throw e 抛出异常的时候,仍然不能确定 所抛出的异常 e 的确切类型。所以,我们需要先进行强转,再抛出。

若描述的有纰漏或者不明白的地方,欢迎指出,一起进步!

 

参考文档:

1、https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.5

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值