咱们常常使用try..catch进行异常处理,可是对于Uncaught Exception是没办法捕获的。对于这类异常如何处理呢? java
回顾一下thread的run方法,有个特别之处,它不会抛出任何检查型异常,但异常会致使线程终止运行。这很是糟糕,咱们必需要“感知”到异常的发生。好比某个线程在处理重要的事务,当thread异常终止,我必需要收到异常的报告(email或者短信)。 app
在jdk 1.5以前貌似没法直接设置thread的Uncaught Exception Handler(具体未验证过),但从1.5开始能够对thread设置handler。 jvm
1. As the handler for a particular thread
当 uncaught exception 发生时, JVM寻找这个线程的异常处理器. 可使用以下的方法为当前线程设置处理器 spa
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默认实现的逻辑以下: code
对应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.