Is there a way to make a global exception-handler in Java. I want to use like this:
\"When an exception is thrown somewhere in the WHOLE program, exit.\"
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/
DefaultUncaughtExceptionHandler is the correct answer. It was revealed to me by Jeff Storey at this location, a few days ago. As u suspected, the "manually" caught exceptions will never be caught by this handler. However i got the following warning :
**- To be compliant to J2EE, a webapp should not use any thread.**
when i have checked my project against good-practice and recommended java coding style with PMD plug-in for Eclipse IDE.
Use Thread.setDefaultUncaughtExceptionHandler. See Rod Hilton's "Global Exception Handling" blog post for an example.
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)
Threads.setDefaultUncaughtExceptionHandler() works but not in all cases. For example, I'm using it in my main() before creating Swing widgets, and it works in the threads created by Swing, such as the AWT event thread or SwingWorker threads.
Sadly, it doesn't have any effect on the thread created by javax.naming.spi.NamingManager.getInitialContext() when using an LDAP URL, using JavaSE 1.6. No doubt there are other exceptions.
You can set the default UncaughtExceptionHandler , which will be used whenever a exception propegates uncaught throughout the system.