← 中文资源

简体中文版本

线程未捕获异常处理器

裸线程逃逸的异常交给默认 UncaughtExceptionHandler 兜底;池里 submit 的任务异常被 Future 承载,必须 get() 才能看到。

阅读英文原文

实现说明

真正干活的是类 CrashReporter,其余都是接线。 不需要 finally——try 头部声明的资源按相反顺序自行关闭。IllegalStateException 在其所在位置无条件抛出——前面没有任何输入检查。

使用要点

  • 直接运行文件,输出会带上标签,比如 handler caught in、future rethrew cause:、main finished——输出的每一行都能指回产生它的那次调用。

常见问题

这个示例会校验输入吗?

不会。示例里没有输入校验——IllegalStateException 在其所在位置无条件抛出,前面没有任何检查。

运行「线程未捕获异常处理器」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 handler caught in、future rethrew cause:、main finished 这类标签。

核心语句

throw new IllegalStateException("boom from pooled task");
throw new IllegalStateException("boom from raw thread");
Thread.setDefaultUncaughtExceptionHandler((thread, thrown) ->
        System.out.println("handler caught in " + thread.getName()
                + ": " + thrown.getMessage()));

代码示例

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CrashReporter {

    public static void main(String[] args) throws InterruptedException {
        Thread.setDefaultUncaughtExceptionHandler((thread, thrown) ->
                System.out.println("handler caught in " + thread.getName()
                        + ": " + thrown.getMessage()));

        // 裸线程里逃逸的异常会走到默认 UncaughtExceptionHandler
        Thread raw = new Thread(() -> {
            throw new IllegalStateException("boom from raw thread");
        }, "raw-worker");
        raw.start();
        raw.join();

        // submit() 的任务异常被 Future 承载:worker 线程不死,UEH 不触发
        try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
            Callable<Void> task = () -> {
                throw new IllegalStateException("boom from pooled task");
            };
            try {
                pool.submit(task).get();
            } catch (ExecutionException wrapped) {
                System.out.println("future rethrew cause: " + wrapped.getCause().getMessage());
            }
        }
        System.out.println("main finished");
    }
}