拦截和推翻Java未处理的异常 [英] Intercept and rethrow a Java unhandled exception

查看:331
本文介绍了拦截和推翻Java未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个catch-all处理程序的方法,但是我需要重新抛出异常,就像它是未被处理的一样,所以调用者(很多)进一步调用堆栈可以处理它。这样做的简单方法是简单的:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆