Thread-Uncaught Exception

本文详细介绍了Java中线程如何处理未捕获的异常。主要包括两种情况:正常结束和因未捕获异常终止。文中还解释了如何为线程设置异常处理器,并探讨了默认处理器的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值