This is on Java 6
Can I have a common method to handle my exceptions – so instead of doing this n times in each method
try {
// Do something
} catch (XException e) {
// Do something
} catch (YException e) {
// Do something
} catch (ZException e) {
// Do something
}
I have
try {
// Do something
} catch (Exception e) {
handleAll (e);
}
and method handleAll(e) does
if e.instanceOf(XException)
else if e.instanceOf(YException)
else if e.instanceOf(ZException)
Is there anything wrong with the 2nd approach?
Update:
My original question was about “centralizing the handling” in one place for both checked and runtime exceptions. The answers have pointed out I should avoid instanceof().
@aioobe’s idea looks very neat to me. Are there any negative opinions on that approach?
There is one minor problem as I see it. Since you really want the
handleAllmethod to rethrow any uncaught exception, it has to be declaredthrows Exception. This means that so does the methods that callhandleAll.If
X-,Y-andZExceptionare allRuntimeExceptionsI see nothing wrong with this. (I may have overlooked something though, as this is the first time I’ve seen this approach.)To be sure that the
instanceofapproach behaves exactly as the catch clauses would, I would consider designing thehandleAll(RuntimeException e)like this though: