UncaughtExceptionHandler throws no exception

I am not sure why the uncaughtException method is not being called.

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); } } 

Program Output:

Throw 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 
+6
source share
3 answers

RuntimeException is RuntimeException from a static initializer, this happens when your main class is loaded. He then caught a system class loader that ends it with an ExceptionInInitializerError , and then exits the JVM. Since the exception is caught, your failed exception handler is never called by default.

+6
source

Your code throws an IOException , and your catch catches an IOException . IOException caught and handled. IIRC UncaughtExceptionHandler uses only the uncaught exception from regular code, not catch . Try temporarily changing your catch to catch some other exception, and see what happens. Remember to change it back!

0
source

Your code is in a static block. If in a very rare case of JVM implementation (if any), the static block is not where you should handle any errors or exceptions, if possible. This is due to the fact that you do not have much control over the execution of the static block (if you do not have a dynamic class loader), which is quite rare.

So, if this is true, move your code to the instance block, and it should work fine.

So, when something unexpected happens in your static block, your application is not expected to continue. Thus, all of these unexpected exceptions in a static block will be thrown by ExceptionInIntiializerError. You can refer to here

0
source

Source: https://habr.com/ru/post/980273/


All Articles