捕获子线程中的异常
2021-05-03 22:27
                         标签:sys   uncaught   service   runnable   ide   let   out   try   new t    如下代码,在 main 线程中,是无法捕获子线程的异常的。 输出: 改造: 输出: 那么主线程为什么不能捕获子线程的异常呢?知乎上有如下解释: ref: 捕获子线程中的异常 标签:sys   uncaught   service   runnable   ide   let   out   try   new t    原文地址:https://www.cnblogs.com/duanguyuan/p/13196770.htmlcatch 子句中的代码不会被执行。import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NaiveExceptionHandling {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        try {
            exec.execute(() -> {
                throw new RuntimeException();
            });
        } catch (RuntimeException e) {
            System.out.println("this msg will not de printed");
        }
        exec.shutdown();
    }
}
Exception in thread "pool-1-thread-1" java.lang.RuntimeException
	at NaiveExceptionHandling.lambda$main$0(NaiveExceptionHandling.java:9)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Process finished with exit code 0
newCachedThreadPool 创建线程池时指定自定义的 ThreadFactory
ThreadFactory 工厂在生产线程时,为其设置 UncaughtExceptionHandler 异常处理import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class NaiveExceptionHandling {
    public static void main(String[] args) {
        ExecutorService exec2 = Executors.newCachedThreadPool(new HandleThreadFactory());
        exec2.execute(() -> {
            throw new RuntimeException();
        });
        exec2.shutdown();
    }
}
class HandleThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        System.out.println("create thread t");
        Thread t = new Thread(r);
        System.out.println("set uncaughtException for t");
        t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("caught " + e);
            }
        });
        return t;
    }
}
create thread t
set uncaughtException for t
caught java.lang.RuntimeException