UncaughtExceptionHandler 未调用

UncaughtExceptionHandler not called

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

class UncaughtExceptionLogger implements Thread.UncaughtExceptionHandler {

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

主要..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 时调用异常处理程序,但这并没有发生。我做错了什么?

看来你必须用单独的线程生成它:

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()
}