示例:
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadFactory;/** * Created by Administrator on 2017/9/6. *///任务class ExceptionThread2 implements Runnable { @Override public void run() { Thread t = Thread.currentThread(); System.out.println("run() by" + t); System.out.println( "eh = " + t.getUncaughtExceptionHandler() ); throw new RuntimeException(); }}//异常处理class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.print("caught" + e); }}//以线程方式启动任务class HandlerThreadFactor implements ThreadFactory { 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; }}public class CaptureUncaughtException { public static void main(String[] args){ ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactor()); exec.execute(new ExceptionThread2()); }}
输出结果:
由于线程的本质特性,使得你不能捕获从线程中逃逸的异常。一旦异常逃出任务的run()方法之外,它就会向外传播到控制台,除非你采取特殊的步骤捕获这些错误的异常。可以用Executor来解决这个问题。
Thread.UncaughtException-Handler是Java SE中的新接口,它允许你在每个Thread对象上都附着一个异常处理器,Thread.UncaughtExceptionHandler.uncaughtException()会在线程因未捕获的异常而临近死亡时被调用,为了使用它,创新了一个新类型的ThreadFactory,它将在每个新创建的Thread对象上附着一个Thread.UncaughtExceptionHandler。将这个工厂传递给Executors创建新的ExecutorService的方法。