/**
* 在Thread类中定义了针对未被捕捉的异常的处理方式,其由JVM调用
* Dispatch an uncaught exception to the handler. This method is
* intended to be called only by the JVM.
*/
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
/**
* 获取对应的异常处理器,如果有手动设置指定,则获取对应的,否则获取该线程对应的线程组对象
*/
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
/* The group of this thread */
private ThreadGroup group;
// null unless explicitly set Thread中定义了未捕捉异常处理器,默认为null,除非通过setUncaughtExceptionHandler方法赋值
private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
// null unless explicitly set 默认的异常处理器,也需要手动进行赋值
private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;
/** ThreadGroup 实现了UncaughtExceptionHandler接口 */
public class ThreadGroup implements Thread.UncaughtExceptionHandler {...}
/** ThreadGroup 提供了默认实现 */
public void uncaughtException(Thread t, Throwable e) {
/*
* 先判断父线程组是否为null,不为null则调用父线程组的uncaughtException方法,
* 而父线程组如果都不重写该方法的话,最终会追溯到system线程组,它没有父线程组
*/
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);
}
}
}
其实看ThreadGroup以及Thread的源码还是很好理清楚逻辑的。