Thread-Uncaught Exception

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".



猜你喜欢

转载自blog.csdn.net/liangking81/article/details/80685760
今日推荐