You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CompletableFuture异常处理:前序任务失败时如何不执行后序任务

问题原因

你使用的whenComplete方法的设计目标就是无论上游CompletableFuture是正常完成还是异常终止,都会执行传入的回调逻辑,通常用于执行资源释放、状态记录这类不管任务成功失败都要完成的收尾操作,因此不符合“A失败则B不运行”的要求。

解决方案

有两类常用实现方式可以满足你的需求:

方案1:使用then*系列回调方法(推荐)

CompletableFuture提供的thenRun、thenAccept、thenApply等回调方法,仅会在上游任务正常完成时触发执行,若上游抛出异常,下游回调会直接跳过,异常会沿调用链向下传递。

  • 若doB不需要使用doA的返回结果,且无返回值,使用thenRun:
CompletableFuture<Void> f = CompletableFuture.supplyAsync(() -> doA(arg))
        .thenRun(() -> doB(arg));
  • 若doB需要使用doA的返回结果,且无返回值,使用thenAccept:
CompletableFuture<Void> f = CompletableFuture.supplyAsync(() -> doA(arg))
        .thenAccept(resultA -> doB(arg, resultA));
  • 若doB有返回值,需要获取doB的执行结果,使用thenApply:
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> doA(arg))
        .thenApply(resultA -> doB(arg, resultA));

方案2:在whenComplete中增加异常判断

如果需要保留现有whenComplete的写法,只需在回调中先判断上游是否抛出异常,仅无异常时执行doB即可:

CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> doA(arg))
        .whenComplete((resultA, throwable) -> {
            if (throwable == null) {
                doB(arg);
            }
        });

内容的提问来源于stack exchange,提问作者user1475172

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:15:05