Java – Central Exception Handler

design-patternsexception handlingjavaobject-oriented

Recently I've been thinking about a general ExceptionHandler, that I could initialize once in my app context and inject it everywhere. The idea that it will have quite simple interface with just public void handle(Exception ex), and then according to exception type it should decide what to do, maybe just log it, or show an alert message to the user, or maybe kill the whole app.

The question is, what is the prettiest way to write such handler without lots of instanceofs? Unfortunately googling gives me only the default exception handler for RuntimeException that was introduced in Java 5.

My first idea is to create an enum, that will have Class field for exception type and it will return the appropriate execution point, for example a concrete exception handler that also implements the interface public void handle(Exception ex), but with the required casting already.

UPD
@alex
I thought about this option and there was a reason I didn't felt ok with it. Suppouse we have code that uses jcifs to acces a file. Simple copy to local storage will require three exception wraps: SMBException, MalformedUrlException and IOException. If I don't use Java 7 catching them may result in repeating three times CenralExceptionHandler.handle(e); which is not that readable. Anyway, when I think about it, it's my fault that I can't use Java 7, so maybe your suggestion is the best. But I'm still in doubts.

Best Answer

What?

No.

You could use method overloading, something like

public void handle(FunnyException e) {
    ...
}

public void handle(NastyException e) {
    ...
}

, and when calling handle, the most appropriate method will be called. : However, I would say that you basically do three things with Exceptions:

  1. Propagate them using throws
  2. Propagate them wrapping them in another kind of Exception
  3. Catch them and do something about them

1 and 2 are not worth it; calling a generic exception handler would be more verbose than just writing the code required.

3 tends to be longer code, however, it is very unusual that you can catch and treat exceptions in the same way in different parts of your code; if you do, this tends to be a code smell; perhaps you need a broader try statement or some disjoint code needs to be brought together.

So I don't think there's a reason to do what you describe.