如何實現主線程捕獲子線程異常
一、基礎概念
我們說過,沒辦法直接在主線程的 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號