I am considering a design where all fatal exceptions will be handled using a custom UncaughtExceptionHandler in a Swing application. This will include unanticipated RuntimeExceptions but also custom exceptions which are thrown when critical resources are unavailable or otherwise fail (e.g. a settings file not found, or a server communication error). The UncaughtExceptionHandler will do different things depending on the specific custom exception (and one thing for all the unanticipated), but in all cases the application will show the user an error message and exit. The alternative would be to keep the UncaughtExceptionHandler for all unanticipated exceptions, but handle all other fatal scenarios close to their origin.
Is the design I’m considering sound, or should I use the alternative? What is the typical approach used for handling fatal exceptions?
Usually, it is hard to find a good exception handling strategy. Every approach has its drawbacks. In particular, Yours is good in some sense (a centralized location for handling failures) but suffers from this flaw:
The exception handler you’re describing will have special handling for each possible exception. Over time it will become a focal point of your application: every time you add new functionality you will also need to add exception-processing logic to your handler. This means that:
Another problem is error recovery. After an exception is thrown (and a some notification is presented to the user), the user want to continue using the application. This means that if your code started modifying the internal data structures and then stopped due to exception, you will need to undo these modifications (or at least get the data structure back to a workable condition) before you allow additional interaction of the user. Achieving this requires a new thinking about the way your data is organized. One possible solution is to DB transactions. On the other hand, this kind of representation is more complicated than plain-old data structures so you need to weigh it against the needs of your app (is it a toy/prototype?)