今天在项目中碰到这样一个问题,我写了如下代码:
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