未调用UncaughtExceptionHandler

时间:2018-09-26 06:16:59

标签: java exception groovy exception-handling uncaughtexceptionhandler

在Groovy / Java中使用UncaughtExceptionHandler时遇到问题。

class UncaughtExceptionLogger implements Thread.UncaughtExceptionHandler {

    @Override
    void uncaughtException(Thread t, Throwable e) {
        //TODO do some logging;
        println "test";
    }

main..groovy

def main(){
    def handler = new UncaughtExceptionLogger();
    Thread.defaultUncaughtExceptionHandler = handler
    String s; 
    s.charAt(10); // causes a NullPointerException but the exception handler is not called 
}

main();

为什么我期望抛出NullPointerException时会调用异常处理程序,但是这不会发生。我在做什么错了?

1 个答案:

答案 0 :(得分:2)

似乎您必须使用单独的线程生成它:

class UncaughtExceptionLogger implements Thread.UncaughtExceptionHandler {
    @Override
    void uncaughtException(Thread t, Throwable e) {
        //TODO do some logging;
        println "test";
    }
}

def main(){
    Thread.defaultUncaughtExceptionHandler = new UncaughtExceptionLogger()
    String s;
    s.charAt(10); // causes a NullPointerException but the exception handler is not called
}

Thread.start {
  main()
}