javastatic-initializer

How to catch ExceptionInInitializerError?


I want to install some kind of global handler to catch any ExceptionInInitializerError which could be thrown from any static block when some class is loading. Currently it dumps a stack trace to the stderr and exits the application. I want to log a stack trace using my logging framework, then exit the application. Is it possible?


Solution

  • It looks like Thread.UncaughtExceptionHandler is what you are looking.

    This answer will provide you with more information.

    In essence you need to install default exception handler as soon as possible:

            Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                if (e instanceof ExceptionInInitializerError) {
                    // do something with you're exception
                    // and than close application
                    System.exit(-1); // passing 
                }
            }
        });