如何实现主线程捕获子线程异常
一、基础概念
我们说过,没办法直接在主线程的 try-catch 中捕获子线程的异常。但是,有的时候子线程中会开启一些IO链接,网络资源等,那么,如何在抛出异常的时候进行处理呢 ?
有几个方案可以实现 ?
1、使用Future
如果想要在主线程能够捕获子线程的异常,可以考虑使用 Callable 和 Future,它们允许主线程获取子线程的执行结果和异常。这样,主线程可以检查子线程是否抛出了异常,并在必要时处理它。以下是一个示例:
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
// 子线程抛出异常
throw new RuntimeException("子线程异常");
});
try {
Integer result = future.get();
System.out.println("子线程结果: " + result);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
System.out.println("捕获到子线程异常"));
}
executor.shutdown();
}
}
以上代码输出结果:

即,子线程中抛出的异常,我们在主线程中的catch块中捕获到了
2、CompletableFuture
Java 8引入了 CompletableFuture,它允许你异步执行任务并处理异常。你可以使用 CompletableFuture.supplyAsync() 来执行任务,并使用 handle()方法 捕获异常。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
// 子线程抛出异常
throw new RuntimeException("子线程异常");
});
future.handle((result, exception) -> {
if (exception != null) {
System.out.println("捕获到子线程异常: " + exception.getMessage());
} else {
System.out.println("子线程结果: " + result);
}
return null;
});

浙公网安备 33010602011771号