简体   繁体   中英

UncaughtExceptionHandler not called

I am having trouble using the UncaughtExceptionHandler in Groovy/Java.

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

Why I expect is the exception handler to be called when the NullPointerException is thrown, however this does not happen. What am I doing wrong?

Seems that you have to spawn it with separate thread:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM