A thread is terminated for one of two reasons:
It dies a natural death because the "run" method exits normally.
It dies abruptly because an uncaught exception terminates the "run" method.
The "run" method of a thread cannot throw any checked exception, like the "InterruptedException", but
it can be terminated by an unchecked exception. In that case, the thread dies.
However, there is no "catch" clause to which the exception can be propagated. Instead, just before the
thread dies, the exception is passed to a hundler for uncaught exceptions.
The handler must belong to a class that implements the "Thread.UncaughtExceptionHandler" interface.
That interface has a single method,
void uncaughtException(Thread t, Throwable e)You can install a hander into any thread with the "setUncaughtExceptionHandler" method. You can also install
a default handler for all threads with the static method "setDefaultUncaughtExceptionHandler" of the "Thread"
class. A replacement handler might use the logging API to send reports of uncaught exception into a log file.
If you don't install a default handler, the default handler is null. However, if you don't install a handler for an individual thread, the handler is the thread's "ThreadGroup" object.
The "ThreadGroup" class implements the "Thread.UncaughtExceptionHandler" interface. Its "uncaughtException"
method takes the following action:
1. If the thread group has a parent, then the "uncaughtException" method of the parent group is called.
2. Otherwise, if the "Thread.getDefaultUncaughtExceptionHandler" method returns a non-null handler, it is called.
3. Otherwise, if the "Throwable" is an instance of "ThreadDeath", nothing happens.
4. Otherwise, the name of the thread and the stack trace of the "Throwable" are printed on "System.err".
本文详细介绍了Java中线程如何处理未捕获的异常。主要包括两种情况:正常结束和因未捕获异常终止。文中还解释了如何为线程设置异常处理器,并探讨了默认处理器的行为。

859

被折叠的 条评论
为什么被折叠?



