Given this stacktrace:
java.lang.RuntimeException:
...
Caused by: com.mypackage.SpecificException
And this try-catch:
try {
ts.init();
} catch (RuntimeException e) {
if (e.getCause() instanceof SpecificException) {
//do something
} else {
throw e;
}
}
I cannot modify the code for SpecificException
nor the method that wraps this exception into a RuntimeException
.
Is there a better way to catch only SpecificException
?
The only mechanism Java provides for selecting which exceptions to catch is the specific exceptions' classes. If you want to discriminate between exceptions of the same class based on their causes, then you need to catch all exceptions of that class, as you demonstrate.
Note, however, that it is problematic to re-throw an exception once you've caught it, because that replaces the original stack trace with a new one specific to the context of the new throw
. That can make debugging a lot more difficult. To avoid that, you would need to wrap the caught exception as the cause of a separate, new exception, and throw that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With