1

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?

Georgi Georgiev
  • 3,854
  • 5
  • 29
  • 39

1 Answers1

2

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()
}
user987339
  • 10,519
  • 8
  • 40
  • 45