Java: Global Exception Handler

前端 未结 6 1401
孤独总比滥情好
孤独总比滥情好 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 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)

提交回复
热议问题