使用 handle 方法可以捕获 completablefuture 执行过程中的异常,并将其转换为正常结果。只需在链式调用中传入 bifunction<t throwable extends r></t> 实现类,当任务抛出异常时,第一个参数为 null,第二个参数包含异常信息;若未发生异常,则第一个参数为计算结果,第二个参数为 null。通过判断第二个参数是否为空,即可决定返回原始结果还是默认值。

handle 如何处理成功与失败两种状态
handle 方法会在异步任务完成(无论是正常结束还是异常结束)后触发回调。它接收两个参数:一个是上游任务的返回值,另一个是抛出的异常。如果任务成功,异常参数为 null;如果任务失败,返回值参数为 null。开发者可以在回调中统一处理这两种情况,将异常“转换”为一个具体的对象或默认值,从而避免后续步骤需要单独处理 exceptionally 分支。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class HandleExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟可能失败的操作
throw new RuntimeException("Service unavailable");
}).handle((result, ex) -> {
if (ex != null) {
// 异常处理:转换为默认结果
return "Default Value";
} else {
// 正常处理:返回原始结果
return result.toUpperCase();
}
});
System.out.println(future.get());
}
}handle 与 exceptionally 的区别是什么
exceptionally 仅针对异常情况提供回调,且只能返回一个结果,无法访问成功时的数据。而 handle 是一个通用的终结者,无论成功与否都会执行,并且能同时访问结果和异常。如果业务逻辑需要在成功时进行数据转换,同时在失败时提供降级方案,handle 比组合使用 thenApply 和 exceptionally 更简洁,因为它在一个步骤中完成了所有逻辑。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompareApproaches {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 使用 handle 统一处理
CompletableFuture<String> handleFuture = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error");
}).handle((res, ex) -> {
if (ex != null) return "Fallback";
return res;
});
// 使用 exceptionally 处理异常
CompletableFuture<String> exceptionalFuture = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Error");
}).exceptionally(ex -> "Fallback");
System.out.println(handleFuture.get());
System.out.println(exceptionalFuture.get());
}
}handle 转换后的结果类型如何确定
handle 的返回值类型由回调函数的返回类型决定。如果上游任务是 CompletableFuture<string></string>,回调函数可以返回任意类型 R,此时生成的新 CompletableFuture 类型为 CompletableFuture<r></r>。这意味着你可以在 handle 中将异常转换为一个完全不同的数据结构,例如从异常中提取错误码并封装成 ErrorDTO 对象,从而实现类型的转换和业务的统一出口。

















