线程中如果有未处理的异常, 放在try catch模块里可能会捕获不到.
此处有个解决方法
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler{
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e); //此处捕获线程中出现的异常
}
}
class HandlerThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
return t;
}
}
调试:
public class CaptureUncaughtException {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread());
}
}
class ExceptionThread implements Runnable{
public void run() {
throw new RuntimeException(); //模拟线程异常
}
}