拦截和推翻Java未处理的异常 [英] Intercept and rethrow a Java unhandled exception
问题描述
try {
...
} catch ex){
// do something here ...
// and rethrow
throw ex;
}
但问题是,因为 throw
语句,Java要求此方法将其自身声明为 throws Exception
,这反过来要求所有调用者处理异常或将其声明为 throws Exception
。所以调用链...
有没有什么简单的方式来重新抛出异常,就像当前的方法没有处理它一样?
您可以执行@radoh所说的内容,并将其包装到一个 RuntimeException
中,但有一个缺点这是你的堆栈跟踪现在被污染,并将显示违规行为你声明的地方 throw new RuntimeException(ex)
。
另一种方法是使用Lomboks SneakyThrows
机制,如下所示:
public static void main(String [] args){
methodWithException();
}
private static void methodWithException(){
try {
throw new Exception(Hello);
} catch(Exception e){
Lombok.sneakyThrow(e);
}
}
您的堆栈跟踪将保持不变,但您不再需要要声明 throws Exception
。
值得阅读文档为什么你应该/不应该这样做
I've coded a method with a catch-all handler, but I need to rethrow the exception as if it were unhandled, so that a caller (much) further up the call stack can handle it. The trivial way to do this is simply:
try {
...
} catch (Exception ex) {
// do something here...
// and rethrow
throw ex;
}
But the problem is that, because of the throw
statement, Java requires this method to declare itself as throws Exception
, which in turn, requires all the callers to handle the exception or declare themselves as throws Exception
. And so on up the call chain...
Is there any simple way to rethrow the exception as if the current method did not handle it?
You could do what @radoh has said and just wrap into a RuntimeException
, but one downside of this is your stacktrace is now polluted and will show the offending line to be where you declare throw new RuntimeException(ex)
.
An alternative is to use Lomboks SneakyThrows
mechanism, like this:
public static void main(String[] args) {
methodWithException();
}
private static void methodWithException() {
try {
throw new Exception("Hello");
} catch (Exception e) {
Lombok.sneakyThrow(e);
}
}
Your stacktrace will remain intact, but you no longer need to declare throws Exception
.
It's worth reading the documentation on why you should/shouldn't do this
这篇关于拦截和推翻Java未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!