异常处理
线程的异常处理
- 无法捕获已逃离线程的异常,一旦异常逃逸到任务的run()方法之外便会扩散到控制台,在execute语句包上try-catch是没用的
- 需要创建一个新的TreadFactory类型,为创建的Tread对象添加Thread.UncaughtExceptionHandler用于添加异常处理程序
``` java
//自定义异常处理
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
}
//绑定异常处理对象的工厂方法
class HandlerThreadFactory implements ThreadFactory {
@Override public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
return t;
}
}
//创建线程池时使用自定义的工厂方法
ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
//设置全局
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());