Java Reference
In-Depth Information
14.12. Threads and Exceptions
Exceptions always occur in a specific thread, due to the actions of that
threadfor example, trying to perform division by zero, or explicitly throw-
ing an exception. Such exceptions are synchronous exceptions and al-
ways remain within the thread. If a "parent" thread wants to know why
a "child" terminated, the child will have to store that information some-
where the "parent" can get it. Placing a thread start invocation in a TRy-
catch block does not catch exceptions that may be thrown by the new
threadit simply catches any exception thrown by start .
When an exception is thrown it causes statements to complete abruptly
and propagates up the call stack as each method invocation completes
abruptly. If the exception is not caught by the time the run method com-
pletes abruptly then it is, by definition, an uncaught exception. At that
point the thread that experienced the exception has terminated and the
exception no longer exists. Because uncaught exceptions are usually a
sign of a serious error, their occurrence needs to be tracked in some way.
To enable this, every thread can have associated with it an instance of
UncaughtExceptionHandler . The UncaughtExceptionHandler interface is a nes-
ted interface of class THRead and declares a single method:
public void uncaughtException(Thread thr, Throwable exc)
Invoked when thr terminated due to exc being thrown.
A thread's uncaught exception handler can be set, if security permissions
allow it, using its setUncaughtExceptionHandler method.
When a thread is about to terminate due to an uncaught exception,
the runtime queries it for its handler by invoking the getUncaughtExcep-
tionHandler method on it , and invokes the returned handler's uncaughtEx-
ception method, passing the thread and the exception as parameters.
The getUncaughtExceptionHandler method will return the handler explicitly
set by the thread's setUncaughtExceptionHandler method, or if no handler
has been explicitly set, then the thread's ThreadGroup object is returned.
 
Search WWH ::




Custom Search