由於線程的本質特性,使得不能捕獲從線程中逃逸的異常。一旦異常逃出任務的main()方法,就會傳播到控制檯中,main方法中try-catch也是沒有作用的。
這就使用到Thread.UncaughtExcuptionHandler接口,這個接口允許沒個Thread對象附着一個異常處理器。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class ExceptionDemo {
class myRunnalbe implements Runnable{
@Override
public void run() {
System.out.println("thread:" + Thread.currentThread());
throw new RuntimeException();// 拋出一個異常
}
}
class myUncaughtExcuptionHandler implements Thread.UncaughtExceptionHandler {
/**
* 處理異常
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Exception::" + e);
}
}
/**
* 線程工廠
* @author Administrator
*
*/
class myThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(new myUncaughtExcuptionHandler());// 設置一個異常處理器
System.out.println("eh::" + t.getUncaughtExceptionHandler());
return t;
}
}
public static void main(String[] args) {
ExceptionDemo demo = new ExceptionDemo();
ExecutorService executor = Executors.newCachedThreadPool(demo.new myThreadFactory());
executor.execute(demo.new myRunnalbe());
}
}
參考博客:https://blog.csdn.net/weixin_42868638/article/details/88541013