Where to handle fatal exceptions

I am considering a project in which all fatal exceptions will be handled using a custom UncaughtExceptionHandler in a Swing application. This will include unforeseen RuntimeExceptions, but also user exceptions that are thrown when critical resources are unavailable or otherwise fail (for example, a configuration file was not found or a communication error with the server). UncaughtExceptionHandler will do different things depending on the particular custom exception (and one for all unforeseen ones), but in all cases the application will show the user an error message and exit. An alternative would be to keep UncaughtExceptionHandler for all unforeseen exceptions, but handle all other fatal scripts close to their origin.

Am I considering a design that I am considering, or should I use an alternative? What is the typical approach used to handle fatal exceptions?

+3
source share
4 answers

It is usually difficult to find a good exception handling strategy. Each approach has its drawbacks. In particular, Yours is good in a way (a centralized place to handle failures), but suffers from this drawback:

The exception handler that you describe will have special handling for every possible exception. Over time, it will become the focus of your application: every time you add new functions, you also need to add exception handling logic for your handler. It means that:

  • , impl. , , . , .
  • ( ) - .

. ( - ), . , - , (, , ), . , . . , , , ( /?)

+2

Swing. , . - , , , .

, , - ErrorMessageException, , . . , , .

" " - . , , , , . .

. , - , .

+1

main try catch; .

public static void main(String[] args) {
    try {
        // everything happens here
        System.exit(0);
    } catch (SpecificException ex) {
        ...
    } catch (AnotherException ex) {
        ...
    } catch (Throwable ex) {
        // deal with anything else.
        ...
    }
    System.exit(1);  // tell the world that we failed.
}
0

If you have a multi-threaded application (for example, most Swing applications), you might want to send exceptions to the central exception processing thread through some asynchronous queue.

0
source

Source: https://habr.com/ru/post/1740644/


All Articles