多线程中异常不会自动传播到主线程,需通过Callable与Future、UncaughtExceptionHandler或重写afterExecute等方式显式处理。

在Java多线程环境中,异常处理比单线程复杂,因为子线程中抛出的异常不会自动传播到主线程。如果不做特殊处理,这些异常可能被静默吞掉,导致问题难以排查。要正确处理多线程中的异常传播,需要显式地捕获并传递异常。
使用 try-catch 在线程内部捕获异常
最基础的方式是在 Runnable 或 Callable 的执行逻辑中手动使用 try-catch 捕获异常。
注意:Runnable.run() 方法不支持抛出受检异常,必须在内部处理。示例:
new Thread(() -> {
try {
// 业务逻辑
int result = 10 / 0;
} catch (Exception e) {
System.err.println("子线程异常:" + e.getMessage());
// 可以记录日志或通知主线程
}
}).start();
使用 Callable 和 Future 获取异常
Callable 允许返回结果并抛出异常,配合 Future.get() 可以将子线程异常传递回主线程。
立即学习“Java免费学习笔记(深入)”;
当调用 future.get() 时,如果子线程执行过程中抛出异常,会封装为 ExecutionException 抛出,原始异常作为其 cause。
示例:
ExecutorService executor = Executors.newSingleThreadExecutor(); Futurefuture = executor.submit(() -> { return 10 / 0; // 抛出 ArithmeticException }); try { Integer result = future.get(); // 此处会抛出 ExecutionException } catch (ExecutionException e) { Throwable cause = e.getCause(); System.err.println("实际异常:" + cause); // ArithmeticException } catch (InterruptedException e) { Thread.currentThread().interrupt(); } executor.shutdown();
设置未捕获异常处理器(UncaughtExceptionHandler)
可以为线程或线程池设置全局的异常处理器,用于捕获未被捕获的运行时异常。
为单个线程设置处理器:
Thread thread = new Thread(() -> {
throw new RuntimeException("测试异常");
});
thread.setUncaughtExceptionHandler((t, e) -> {
System.err.println(t.getName() + " 发生异常:" + e.getMessage());
});
thread.start();
为线程池设置默认处理器:
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
System.err.println("全局异常:" + t.getName() + ", 异常:" + e.getMessage());
});
在线程池中统一处理异常
自定义 ThreadPoolExecutor 并重写 afterExecute 方法,可以在任务执行后检查异常状态。
示例:
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t != null) {
System.err.println("线程池任务异常:" + t);
}
}
};
executor.execute(() -> {
throw new RuntimeException("任务异常");
});
基本上就这些。关键在于意识到线程间的异常不会自动传播,必须通过 Future、异常处理器或显式捕获来传递和处理。选择哪种方式取决于你使用的是 Runnable 还是 Callable,以及是否使用线程池。










