1、因为线程的本质特性,一般无法捕获从线程逃逸的异常。异常逃出任务run方法,会向外传播到控制台。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExceptionThread implements Runnable {
public void run(){
throw new RuntimeException();//抛出的异常在main中用try-catch无法捕获
}
public static void main(String[] args) {
/*ExecutorService executorService=Executors.newCachedThreadPool();
executorService.execute(new ExceptionThread());*/
try{
ExecutorService executorService=Executors.newCachedThreadPool();
executorService.execute(new ExceptionThread());
} catch (RuntimeException e) {
System.out.println("Exception has been handled");
}
}
}
/*Exception in thread "pool-1-thread-1" java.lang.RuntimeException
at ExceptionThread.run(ExceptionThread.java:8)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)*/
2、现在,可以用Executor来捕获异常。
在程序中添加跟踪机制。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class CaptureUncaughtException {
static public class ExceptionThread implements Runnable{
public void run(){
Thread thread=Thread.currentThread();
System.out.println("run by "+thread);
System.out.println("eh= "+thread.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
static public class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler{
public void uncaughtException(Thread t,Throwable e){
System.out.println("caught "+e);
}
}
static public class HandleThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r) {
System.out.println(this+" creating new thread");
Thread thread=new Thread(r);
thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
System.out.println("eh= "+thread.getUncaughtExceptionHandler());
return thread;
}
}
public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool(
new HandleThreadFactory());
executorService.execute(new ExceptionThread());
}
}
/*CaptureUncaughtException$HandleThreadFactory@165a3c2 creating new thread
eh= CaptureUncaughtException$MyUncaughtExceptionHandler@11e0c13
run by Thread[Thread-0,5,main]
eh= CaptureUncaughtException$MyUncaughtExceptionHandler@11e0c13
CaptureUncaughtException$HandleThreadFactory@165a3c2 creating new thread
eh= CaptureUncaughtException$MyUncaughtExceptionHandler@1242b11
caught java.lang.RuntimeException*/