Java uncaught global exception handler

后端 未结 3 1235
北恋
北恋 2020-12-01 04:05

I have an application and need to code a custom global uncaught exception handler. I\'ve read all the stackoverflow threads and each one of them is just missing a clear and

3条回答
  •  爱一瞬间的悲伤
    2020-12-01 04:24

    You can set UncaughtExceptionHandler for the thread controlling the code above:

    // t is the parent code thread
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    
        public void uncaughtException(Thread t, Throwable e) {
           LOGGER.error(t + " throws exception: " + e);
        }
     });
    

    Java docs for UncaughtExceptionHandler -

    When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments

    the setUncaughtExceptionHandler is commonly used to free memory or kill threads that the system will not be able to kill, and perhaps, remain zombie.

    A real example:

    Thread t = new Thread(new MyRunnable());
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    
        public void uncaughtException(Thread t, Throwable e) {
           LOGGER.error(t + " throws exception: " + e);
        }
    });
    t.start();
    
    //outside that class
    class MyRunnable implements Runnable(){
        public void run(){
            throw new RuntimeException("hey you!");
        }
    }
    

提交回复
热议问题