0

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?

vbezhenar
  • 11,148
  • 9
  • 49
  • 63

2 Answers2

1

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 
            }
        }
    });
Community
  • 1
  • 1
river
  • 774
  • 5
  • 16
  • Thanks, it works. It seems that System.exit isn't necessary, as JVM exits anyway, so I just log exception in the handler. – vbezhenar Jul 03 '16 at 13:47
1

Maybe you can make a global exception handler and just filter your exception out of it.

Example

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) {
        if (e instanceof ExceptionInInitializerError) {
            //Your handler code
        }
    }
});
Fabio Widmer
  • 529
  • 1
  • 7
  • 19