Java异常体系图
为什么需要UncaughtExceptionHandler?
首先看一个例子,从0打印到1000,中间子线程抛出异常
public class ExceptionInChildThread implements Runnable {
public static void main(String[] args) {
new Thread(new ExceptionInChildThread()).start();
for (int i=0;i<1000;i++){
System.out.println(i);
}
}
@Override
public void run() {
throw new RuntimeException();
}
}
从结果会发现,抛出的异常基本上被打印的数字埋没了,很难找到。并且,子线程的异常不能通过在外面套用try/catch的方式进行捕获。
捕获线程异常的错误例子(套用try/catch)
public class CantChtchDirectly implements Runnable {
public static void main(String[] args)