Java Reference
In-Depth Information
In the previous code, an UncaughtExceptionHandler is registered on the
currentThread . Just like Solution 1, UncaughtExceptionHandler is a func-
tional interface, so it is possible to utilize a lambda expression to implement the excep-
tion handler.
How It Works
The Thread.defaultUncaughtExceptionHandler() will be invoked for
each unchecked exception that has not been caught. When the UncaughtExcep-
tionHandler() handles an exception, it means that there was no try / catch
block in place to catch the exception. As such, the exception bubbled all the way up the
thread stack. This is the last code executed on that thread before it terminates. When an
exception is caught on either the thread's or the default's UncaughtExcep-
tionHandler() , the thread will terminate. The UncaughtExceptionHand-
ler() can be used to log information on the exception to help pinpoint the reason of
the exception.
In the second solution, the UncaughtExceptionHandler() is set up spe-
cifically for the current thread. When the thread throws an exception that is not caught,
it will bubble up to the UncaughtExceptionHandler() of the thread. If this is
not present, it will bubble up to the defaultUncaughtExceptionHandler() .
Again, in either situation, the thread originating the exception will terminate.
Tip When dealing with multiple threads, it is always good practice to explicitly
name the threads. It makes life easier to know exactly which thread caused the excep-
tion, rather than having to trace down an unknown thread named like Thread-## (the
default naming pattern of unnamed threads).
9-6. Managing Resources with try/catch
Blocks
Problem
Search WWH ::




Custom Search