考虑下面的代码:
@Test(expected = NullPointerException.class)
public void testSaveEmptyApplication() {
try {
Application application = new Application();
Application result = applicationService.save(application);
} catch (Exception e) {
if(e instanceof UncheckedServiceException) {
throw e.getCause(); // java.lang.Throwable, compiler error
}
}
}如何重新抛出Throwable?
发布于 2021-03-24 13:57:52
问题是testSaveEmptyApplication没有声明为抛出任何检查过的异常。但是e.getCause()返回Throwable,这是一个检查过的异常。因此,您在示例代码中所做的事情违反了Java的检查异常规则。
如果您知道原因确实是RuntimeException,那么您可以这样做
throw (RuntimeException) e.getCause();注意事项:
ClassCastException,它会挤压您试图重新抛出的原因异常。如果原因是Error,上面的代码也会中断,但你可以处理它;例如,像这样。
可抛出的原因= e.getCause();如果(RuntimeException的原因实例){ throw (RuntimeException)原因;} else if (实例错误的原因){抛出(错误)原因;} else {抛出新的AssertionError(“意外异常类”,原因);}
这一切都有点麻烦。但这是您首先为包装异常而付出的代价。
发布于 2021-03-24 13:29:40
我能想到的一个解决方案是:
catch子句为:
try {
// ...
} catch (Exception e) {
if(e instanceof UncheckedServiceException) {
if(e.getCause() instanceof NullPointerException) {
throw new NullPointerException(e.getCause().getMessage());
}
}
}否则,更改方法签名,如下所示:
public void method() throws Throwable {
// ...
}https://stackoverflow.com/questions/66775187
复制相似问题