Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common / centralized method to handle multiple exceptions

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?

like image 766
shinynewbike Avatar asked Aug 02 '11 09:08

shinynewbike


People also ask

How can you handle multiple exceptions in a program?

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.

What is centralized error handling?

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.


2 Answers

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) {
        ...
    }
}
like image 153
aioobe Avatar answered Sep 30 '22 08:09

aioobe


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

like image 44
nidhin Avatar answered Sep 30 '22 09:09

nidhin