Java setUncaughtExceptionHandler() doesn't work when exception happen

138 Views Asked by At

I've got test code to see if I can set exception handler:

class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("An exception has been captured\n");
        System.out.printf("Thread:%s\n", t.getName());
        System.out.printf("Exception: %s: %s:\n", e.getClass().getName(), e.getMessage());
        System.out.printf("Stack Trace:\n");
        System.out.printf("Thread status:%s\n", t.getState());
    }
}
public class TestUncaughtException {
    public static void main(String[] args) {
        Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());
        System.out.println(Integer.parseInt("ff"));
    }
}

Running it using maven, it prints:

java.lang.NumberFormatException: For input string: "ff"
    at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)
    at java.lang.Integer.parseInt (Integer.java:580)
    at java.lang.Integer.parseInt (Integer.java:615)
    at TestUncaughtException.main (TestUncaughtException.java:18)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:254)
    at java.lang.Thread.run (Thread.java:748)

Seems MyExceptionHandler is not working, as uncaughtException is not called.

Where did I get wrong?

0

There are 0 best solutions below