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.