使用 completablefuture 处理异步异常的核心方法是链式调用 exceptionally() 或 handle()。在构建异步任务时,直接挂载这些方法可以捕获并转换执行过程中抛出的任何异常,从而避免程序崩溃或返回未处理的错误对象。

exceptionally() 与 handle() 的区别是什么
exceptionally() 专门用于处理异常情况,它接收一个函数,该函数的参数是捕获到的 Throwable,返回值是替代的正常结果;如果任务正常完成,该函数不会被调用。而 handle() 则是一个通用的回调,无论任务成功还是失败都会执行,它同时提供结果和异常两个参数,适合需要统一处理逻辑的场景。

import java.util.concurrent.CompletableFuture;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("Simulated Error");
}
return "Success";
});
// 使用 exceptionally 处理异常
CompletableFuture<string> handledFuture = future.exceptionally(ex -> {
System.out.println("Caught exception: " + ex.getMessage());
return "Fallback Value";
});
// 使用 handle 处理所有情况
CompletableFuture<string> universalHandled = future.handle((result, ex) -> {
if (ex != null) {
return "Error Handled: " + ex.getMessage();
}
return "Result: " + result;
});
System.out.println(handledFuture.join());
System.out.println(universalHandled.join());
}
}</string></string></string>
如何结合 thenApply() 实现异常隔离
在异步链中,如果在 thenApply() 之前发生异常,后续的 thenApply() 将不会执行,而是直接传递异常。为了隔离这种影响,可以在每个关键步骤后添加 exceptionally(),或者使用 whenComplete() 来记录日志而不中断流程。这样可以确保单个任务的失败不会导致整个链条的静默失败,同时允许你根据具体需求决定是重试、降级还是向上抛出。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。

import java.util.concurrent.CompletableFuture;
public class IsolatedExceptionDemo {
public static void main(String[] args) {
CompletableFuture<integer> step1 = CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException("Step 1 Failed");
return 10;
});
// 即使 step1 失败,step2 仍然会执行,因为 step1 已经通过 exceptionally 处理了异常
CompletableFuture<integer> step2 = step1.exceptionally(ex -> 0)
.thenApply(res -> res * 2);
System.out.println(step2.join()); // 输出 0
}
}</integer></integer>
当多个 CompletableFuture 组合时如何处理异常
当使用 allOf() 或 anyOf() 组合多个 CompletableFuture 时,异常处理变得复杂,因为 join() 可能会抛出 CompletionException。最佳实践是在每个单独的 CompletableFuture 上预先绑定 exceptionally() 或 handle(),将它们转换为正常的返回值,然后再进行组合。这样,组合后的 Future 就不会再包含未处理的异常,简化了最终结果的获取逻辑。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










