Java Reference
In-Depth Information
Listing 7.24.
UncaughtExceptionHandler
Interface.
What the handler should do with an uncaught exception depends on your quality-of-service
requirements. The most common response is to write an error message and stack trace to the
application log, as shown in
Listing 7.25
. Handlers can also take more direct action, such as
trying to restart the thread, shutting down the application, paging an operator, or other cor-
rective or diagnostic action.
Listing 7.25.
UncaughtExceptionHandler
that Logs the Exception.
In long-running applications, always use uncaught exception handlers for all threads that at
least log the exception.
To set an
UncaughtExceptionHandler
for pool threads, provide a
ThreadFactory
to the
ThreadPoolExecutor
constructor. (As with all thread manipulation, only the
thread's owner should change its
UncaughtExceptionHandler
.) The standard thread
pools allow an uncaught task exception to terminate the pool thread, but use a
try-fi-
nally
block to be notified when this happens so the thread can be replaced. Without an
uncaught exception handler or other failure notification mechanism, tasks can appear to fail
silently, which can be very confusing. If you want to be notified when a task fails due to an
exception so that you can take some task-specific recovery action, either wrap the task with a
Runnable
or
Callable
that catches the exception or override the
afterExecute
hook
in
ThreadPoolExecutor
.