Issue
I want to catch an exception, that is nested into another exception. I'm doing it currently this way:
} catch (RemoteAccessException e) {
if (e != null && e.getCause() != null && e.getCause().getCause() != null) {
MyException etrp = (MyException) e.getCause().getCause();
...
} else {
throw new IllegalStateException("Error at calling service 'service'");
}
}
Is there a way to do this more efficient and elegant?
Solution
There is no more elegant way of selectively "catching" nested exceptions. I suppose if you did this kind of nested exception catching a lot, you could possibly refactor the code into a common utility method. But it still won't be either elegant or efficient.
The elegant solution is to do away with the exception nesting. Either don't chain the exceptions in the first place, or (selectively) unwrap and rethrow the nested exceptions further up the stack.
Exceptions tend to be nested for 3 reasons:
You have decided that the details of the original exception are unlikely to be useful for the application's error recovery ... but you want to preserve them for diagnostic purposes.
You are implementing API methods that don't allow a specific checked exception but your code unavoidably throws that exception. A common workaround is to "smuggle" the checked exception inside an unchecked exception.
You are being lazy and turning a diverse set of unrelated exceptions into a single exception to avoid having lots of checked exceptions in your method signature1.
In the first case, if you now need to discriminate on the wrapped exceptions, then your initial assumptions were incorrect. The best solution is change method signatures so that you can get rid of the nesting.
In the second case, you probably should unwrap the exceptions as soon as control has passed the problematic API method.
In the third case, you should rethink your exception handling strategy; i.e. do it properly2.
1 - Indeed, one of the semi-legitimate reasons for doing this has gone away due to the introduction of the multi-exception catch syntax in Java 7.
2 - Don't change your API methods to throws Exception
. That only makes things worse. You now have to either "handle" or propagate Exception
each time you call the methods. It is a cancer ...
Answered By - Stephen C
Answer Checked By - Mary Flores (JavaFixing Volunteer)