1

我在使用UncaughtExceptionHandlerGroovy/Java 时遇到问题。

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,但这不会发生。我究竟做错了什么?

4

1 回答 1

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()
}
于 2018-09-26T07:41:24.067 回答