Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UncaughtExceptionHandler not catching exception

I'm unsure why the uncaughtException method is not being invoke.

static
{
    /**
     * Register a logger for unhandled exceptions.
     */
    Thread.UncaughtExceptionHandler globalExceptionHandler = new Thread.UncaughtExceptionHandler()
    {
        @Override
        public void uncaughtException(Thread t, Throwable e)
        {
            System.out.println("handle exception."); // can also set bp here that is not hit.
        }
    };

    Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
    Thread.currentThread().setUncaughtExceptionHandler(globalExceptionHandler);

    /**
     * Register gateway listen port.
     */
    try
    {
       // some stuff that raises an IOException
    }
    catch (IOException e)
    {
        System.out.println("Throwing exception");
        throw new RuntimeException(e);
    }

}

The program output is:

Throwing exception

java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: java.io.FileNotFoundException: blah.jks 
    (The system cannot find the file specified)
...some stack trace...
Exception in thread "main" 
Process finished with exit code 1
like image 317
Dejas Avatar asked Dec 29 '14 21:12

Dejas


1 Answers

The RuntimeException being raised from a static initializer, it happens when your main class is loaded. It is then caught by the system class loader, which wraps it into an ExceptionInInitializerError, then exits from the JVM. Since the exception is caught, your default uncaught exception handler is never invoked.

like image 95
Lolo Avatar answered Oct 20 '22 00:10

Lolo