exceptionally、handle 和 whencomplete 的核心区别在于它们对异常的处理方式以及返回值类型的不同。exceptionally 专门用于捕获异常并返回一个替代值,它会将正常结果丢弃;handle 是通用的回调方法,无论是否发生异常都会执行,且能同时访问结果和异常对象,适合进行统一的结果转换或日志记录;whencomplete 则是一个纯副作用回调,它不改变 completablefuture 的完成状态,也不提供返回值来替换原结果,仅用于执行清理工作或通知监听者。

exceptionally 如何捕获异常并返回默认值
exceptionally 仅在任务抛出异常时触发,如果任务正常完成,该阶段会被跳过。它的输入参数是 Throwable,返回值类型必须与上游任务的 CompletableFuture<t></t> 中的泛型 T 一致。这意味着你必须在异常分支中提供一个合法的 T 类型对象作为“兜底”值。如果上游没有异常,exceptionally 不会执行,下游继续接收原始的正常结果。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ExceptionallyDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 场景1:抛出异常
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Network Error");
}).exceptionally(ex -> {
System.out.println("Caught exception: " + ex.getMessage());
return "Default Value"; // 必须返回 String
});
System.out.println("Result 1: " + future1.get());
// 场景2:正常完成
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Success")
.exceptionally(ex -> {
return "Should not print this";
});
System.out.println("Result 2: " + future2.get());
}
}
handle 如何统一处理成功与失败结果
handle 是 BiFunction<t throwable u></t> 的实现,它保证在任务完成(无论是正常结束还是异常结束)后都会执行。它接收两个参数:result(如果发生异常则为 null)和 throwable(如果正常完成则为 null)。这使得你可以在同一个回调中根据状态决定返回什么值。与 exceptionally 不同,handle 允许你改变返回值的类型(从 T 变为 U),并且即使发生异常,它也会将处理后的结果传递给下一个阶段,而不是重新抛出异常(除非你在 handle 内部再次抛出运行时异常)。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class HandleDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 场景1:正常结果
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Data")
.handle((result, ex) -> {
if (ex != null) {
return "Error Handled: " + ex.getMessage();
}
return result.toUpperCase();
});
System.out.println("Handle Result 1: " + future1.get());
// 场景2:异常结果
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Fail");
}).handle((result, ex) -> {
if (ex != null) {
return "Recovered from: " + ex.getMessage();
}
return result;
});
System.out.println("Handle Result 2: " + future2.get());
}
}
whenComplete 在不改变结果的情况下执行副作用
whenComplete 类似于 handle,也接收 result 和 throwable,但它的函数签名是 Consumer super T> 的变体(实际上是 BiConsumer<t throwable></t>),意味着它没有返回值。它的作用是执行一些不影响后续流程的操作,比如记录日志、关闭资源或发送监控指标。重要的是,whenComplete 不会吞掉异常,也不会改变上游的结果。如果上游抛出了异常,whenComplete 执行完后,异常会继续向下游传播,导致后续的 thenApply 或 get() 抛出 ExecutionException。如果你需要在 whenComplete 中处理异常而不让它传播,应该使用 handle 或 exceptionally。


















