CompletableFuture异常处理

在Java中,CompletableFuture是一个用于异步编程的强大工具,它代表了异步计算的结果。在使用CompletableFuture时,正确地处理异常是非常重要的,以确保程序的健壮性和可靠性。以下是一些处理CompletableFuture异常的常见方法:

1. 使用exceptionally方法

exceptionally方法允许你为CompletableFuture设置一个异常处理器。当CompletableFuture完成时,无论其正常完成还是异常完成,都会执行此处理器。

 
 
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
throw new RuntimeException("An error occurred");
})
.exceptionally(ex -> {
System.err.println("Exception caught: " + ex.getMessage());
return null; // 返回null或其他值以避免后续操作失败
});

2. 使用handle方法

handle方法允许你处理正常结果和异常情况。它接收两个参数:一个是结果,另一个是异常。

 
 
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("An error occurred");
})
.handle((result, ex) -> {
if (ex != null) {
System.err.println("Exception caught: " + ex.getMessage());
return "Error occurred"; // 返回默认值或错误信息
}
return result; // 处理正常结果
});

3. 使用whenComplete方法

whenComplete方法在CompletableFuture完成时(无论是正常完成还是异常完成)都会执行,但它不用于转换结果。它通常用于执行清理操作,如关闭资源。

 
 
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
throw new RuntimeException("An error occurred");
})
.whenComplete((result, ex) -> {
if (ex != null) {
System.err.println("Exception caught: " + ex.getMessage());
}
});

4. 使用allOfanyOf处理多个CompletableFuture的异常

当你有多个CompletableFuture需要同时处理时,可以使用CompletableFuture.allOf()CompletableFuture.anyOf()。你可以在这些方法的返回结果上使用异常处理方法来统一处理所有或任何一个的异常。

 
 
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
throw new RuntimeException("Error in future 1");
});
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
// Some other code that might throw an exception
});
 
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
allFutures.exceptionally(ex -> {
System.err.println("Exception caught: " + ex.getMessage());
return null; // 处理异常并返回null或其他值以避免后续操作失败
});

5. 使用joinget方法时处理异常

当你调用join()get()方法阻塞等待结果时,可以使用try-catch块来捕获可能抛出的异常。

 
 
try {
String result = future.join(); // 或者 future.get(); 但通常建议使用join()因为它更灵活(例如可以与lambda表达式一起使用)
// 处理结果
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}

通过上述方法,你可以有效地处理CompletableFuture中的异常,确保你的异步代码既健壮又易于维护。

posted @ 2025-04-07 16:11  甜菜波波  阅读(1004)  评论(0)    收藏  举报