Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to catch only specific cause(s) of an exception?

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?

like image 489
Jonathan C Avatar asked Mar 25 '15 15:03

Jonathan C


1 Answers

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.

like image 72
John Bollinger Avatar answered Sep 21 '22 12:09

John Bollinger