【问题标题】:UncaughtExceptionHandler not called未调用 UncaughtExceptionHandler
【发布时间】:2018-09-26 06:16:58
【问题描述】:

我在 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 时调用异常处理程序,但是这不会发生。我做错了什么?

【问题讨论】:

    标签: java exception groovy exception-handling uncaughtexceptionhandler


    【解决方案1】:

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

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

    【讨论】:

    • 这背后的原因是什么? Groovy 不是在线程中运行吗?
    猜你喜欢
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    相关资源
    最近更新 更多