Search code examples
javagroovyexceptionuncaughtexceptionhandler

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?


Solution

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