javaexception

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?


Solution

  • 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.