Reputation: 10326
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?
Upvotes: 1
Views: 1651
Reputation: 140328
You have exactly two options with (checked) exceptions:
try
/catch
(which may include rethrowing as a different exception type)throws
the exception.If you want to rethrow the exception as if this method did not catch it, your only option is 2.
Note: you only want to catch (Exception e)
if a method in the try
block actually throws Exception
. Otherwise, catch the specific exception types.
Upvotes: 3
Reputation: 21184
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
Upvotes: 2