Java: Global Exception Handler

Solution 1:

Use Thread.setDefaultUncaughtExceptionHandler. See Rod Hilton's "Global Exception Handling" blog post for an example.

Solution 2:

You can set the default UncaughtExceptionHandler , which will be used whenever a exception propegates uncaught throughout the system.

Solution 3:

Here's an example which uses Logback to handle any uncaught exceptions:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) {
        LoggerFactory.getLogger("CustomLogger").error("Uncaught Exception in thread '" + t.getName() + "'", e);
        System.exit(1);
    }
});

This can also be done on a per-thread basis using Thread.setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler)

Solution 4:

For clarification, use setDefaultUncaughtExceptionHandler for standalone Java applications or for instances where you are sure you have a well-defined entry point for the Thread.

For instances where you do not have a well-defined entry point for the Thread, for example, when you are running in a web server or app server context or other framework where the setup and teardown are handled outside of your code, look to see how that framework handles global exceptions. Typically, these frameworks have their own established global exception handlers that you become a participant in, rather than define.

For a more elaborate discussion, please see http://metatations.com/2011/11/20/global-exception-handling-in-java/