0
点赞
收藏
分享

微信扫一扫

CompletableFuture.supplyAsync方法执行异步任务时,捕获异常的几种方式

IT影子 2023-08-15 阅读 64
  1. 在thenApply()/thenAccept()等方法中通过try/catch块捕获:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // 可能抛出异常的代码
}).thenApply(res -> {
    try {
        // 使用结果的代码 
        return res;
    } catch (Exception ex) {
        // 处理异常
        return "error"; 
    }
});
  1. 使用 exceptionally() 方法处理异常:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // 可能抛出异常的代码    
}).exceptionally(ex -> {
    // 处理异常
    return "error";
});
  1. 在thenApplyAsync()/thenAcceptAsync()等方法中处理:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    // 可能抛出异常的代码
}).thenApplyAsync(res -> {
    // 使用结果的代码
    return res;
}, executor).exceptionally(ex -> {
    // 处理异常
    return "error";
});
  1. 使用 whenComplete() 方法处理正常执行和异常情况:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
   // 可能抛出异常的代码 
}).whenComplete((res, ex) -> {
    if(ex != null){
       // 处理异常
    } else {
       // 使用结果
    }
});

通过这些方式,可以很好地处理CompletableFuture异步任务中可能出现的异常。

举报

相关推荐

0 条评论