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?
By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.
Centralized way involves some sort of central database or storage of errors (usually a module or a header file) where are all the error messages stored. In code you pass an error code to some function and it does all the work for you. A big plus of this approach is that you have everything in one place.
There is one minor problem as I see it. Since you really want the handleAll
method to rethrow any uncaught exception, it has to be declared throws Exception
. This means that so does the methods that call handleAll
.
If X-
, Y-
and ZException
are all RuntimeExceptions
I 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 instanceof
approach behaves exactly as the catch clauses would, I would consider designing the handleAll(RuntimeException e)
like this though:
private void handleAll(RuntimeException e) {
try {
throw e;
} catch (XException xe) {
...
} catch (YException xe) {
...
} catch (ZException xe) {
...
}
}
It's a BAD approach. It will reduce LOC (Line Of Code) but it will create difficult to understand, More resource dependent (It requires more memory and processing capacity). it also reduce Readability.
So first one is the best one
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