- 在thenApply()/thenAccept()等方法中通过try/catch块捕获:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 可能抛出异常的代码
}).thenApply(res -> {
try {
// 使用结果的代码
return res;
} catch (Exception ex) {
// 处理异常
return "error";
}
});
- 使用 exceptionally() 方法处理异常:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 可能抛出异常的代码
}).exceptionally(ex -> {
// 处理异常
return "error";
});
- 在thenApplyAsync()/thenAcceptAsync()等方法中处理:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 可能抛出异常的代码
}).thenApplyAsync(res -> {
// 使用结果的代码
return res;
}, executor).exceptionally(ex -> {
// 处理异常
return "error";
});
- 使用 whenComplete() 方法处理正常执行和异常情况:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 可能抛出异常的代码
}).whenComplete((res, ex) -> {
if(ex != null){
// 处理异常
} else {
// 使用结果
}
});
通过这些方式,可以很好地处理CompletableFuture异步任务中可能出现的异常。