Java: Global Exception Handler

前端 未结 6 1371
孤独总比滥情好
孤独总比滥情好 2020-11-27 03:06

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.\"


        
相关标签:
6条回答
  • 2020-11-27 03:55

    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/

    0 讨论(0)
  • 2020-11-27 03:58

    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.

    0 讨论(0)
  • 2020-11-27 04:04

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

    0 讨论(0)
  • 2020-11-27 04:04

    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)

    0 讨论(0)
  • 2020-11-27 04:05

    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.

    0 讨论(0)
  • 2020-11-27 04:09

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

    0 讨论(0)
提交回复
热议问题