您的位置:首页 > 其它

关于未捕获异常(Uncaught Exception)的处理

2015-10-08 10:30 756 查看
我们经常使用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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: