recover 没有捕获异常_关于未捕获异常(Uncaught Exception)的处理

我们经常使用try..catch进行异常处理,但是对于Uncaught Exception是没办法捕获的。对于这类异常如何处理呢?

回顾一下thread的run方法,有个特别之处,它不会抛出任何检查型异常,但异常会导致线程终止运行。这非常糟糕,我们必须要“感知”到异常的发生。比如某个线程在处理重要的事务,当thread异常终止,我必须要收到异常的报告(email或者短信)。

在jdk 1.5之前貌似无法直接设置thread的Uncaught Exception Handler(具体未验证过),但从1.5开始可以对thread设置handler。

1. As the handler for a particular thread

当 uncaught exception 发生时, JVM寻找这个线程的异常处理器. 可以使用如下的方法为当前线程设置处理器

public class MyRunnable implements Runnable {

public void run() {

// Other Code

Thread.currentThread().setUncaughtExceptionHandler(myHandler);

// Other Code

}

}

2. As the handler for a particular thread group

如果这个线程属于一个线程组,且线程级别并未指定异常处理器(像上节As the handler for a particular thread中那样),jvm则试图调用线程组的异常处理器。

线程组(ThreadGroup)实现了Thread.UncaughtExceptionHandler接口,所以我们只需要在ThreadGroup子类中重写实现即可

public class ThreadGroup implements Thread.UncaughtExceptionHandler

java.lang.ThreadGroup 类uncaughtException默认实现的逻辑如下:

如果父线程组存在, 则调用它的uncaughtException方法.

如果父线程组不存在, 但指定了默认处理器 (下节中的As the default handler for the application), 则调用默认的处理器

如果默认处理器没有设置, 则写错误日志.但如果 exception是ThreadDeath实例的话, 忽略。

对应JDK的源码:

public void uncaughtException(Thread t, Throwable e) {

if (parent != null) {

parent.uncaughtException(t, e);

} else {

Thread.UncaughtExceptionHandler ueh =

Thread.getDefaultUncaughtExceptionHandler();

if (ueh != null) {

ueh.uncaughtException(t, e);

} else if (!(e instanceof ThreadDeath)) {

System.err.print("Exception in thread \""

+ t.getName() + "\" ");

e.printStackTrace(System.err);

}

}

}

3. As the default handler for the application (JVM)

Thread.setDefaultUncaughtExceptionHandler(myHandler);

不写了,打字太累,什么时候能有好用的语音输入editor.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值