使用exceptionally、handle、whenComplete等方法处理CompletableFuture异常,确保异步异常不被忽略。1. exceptionally提供默认值;2. handle统一处理结果和异常;3. 在回调链中通过exceptionally捕获中间异常;4. whenComplete用于日志或清理。优先用handle获得完整控制,避免异常丢失。

在Java中使用CompletableFuture进行异步编程时,异常处理是关键的一环。由于异步任务可能在后台线程中执行,未捕获的异常不会直接抛出到主线程,容易被忽略。因此,必须显式地处理异常,以确保程序的健壮性。
1. 使用 exceptionally 方法捕获异常
该方法用于在发生异常时提供一个备选结果,类似于 try-catch 中的 catch 块。
它接收一个函数,当原始 CompletableFuture 发生异常时,会调用这个函数,并返回一个新的 CompletableFuture。
CompletableFuturefuture = CompletableFuture .supplyAsync(() -> { if (true) throw new RuntimeException("Something went wrong"); return "Hello"; }) .exceptionally(ex -> { System.out.println("Caught exception: " + ex.getMessage()); return "Fallback value"; }); System.out.println(future.join()); // 输出: Fallback value
2. 使用 handle 方法统一处理结果和异常
handle 比 exceptionally 更灵活,无论是否发生异常都会执行,接收两个参数:结果和异常。
立即学习“Java免费学习笔记(深入)”;
适用于需要根据结果或异常做不同处理的场景。
CompletableFuturefuture = CompletableFuture .supplyAsync(() -> { return 10 / 0; // 抛出 ArithmeticException }) .handle((result, ex) -> { if (ex != null) { System.out.println("Error occurred: " + ex.getMessage()); return "Recovered from error"; } return "Result: " + result; }); System.out.println(future.join()); // 输出: Recovered from error
3. 在回调中处理异常(如 thenApply、thenAccept)
如果在 thenApply 等链式操作中抛出异常,该异常也会被封装。可以在后续使用 exceptionally 或 handle 捕获。
CompletableFuturefuture = CompletableFuture .completedFuture("5") .thenApply(s -> Integer.parseInt(s)) .thenApply(num -> num / 0) // 异常在此处抛出 .exceptionally(ex -> { System.out.println("In chain error: " + ex.getCause().getMessage()); return -1; }); System.out.println(future.join()); // 输出: -1
4. 主动监听异常 —— 使用 whenComplete
该方法用于副作用处理,比如日志记录或资源清理,不改变结果值。
它接收结果和异常,但返回的 CompletableFuture 仍保留原始的结果或异常。
CompletableFuturefuture = CompletableFuture .supplyAsync(() -> { throw new RuntimeException("Oops!"); }) .whenComplete((result, ex) -> { if (ex != null) { System.out.println("Logging failure: " + ex.getMessage()); } else { System.out.println("Success: " + result); } }) .exceptionally(ex -> "Default"); System.out.println(future.join()); // 输出: Default
基本上就这些。关键是别让异常在异步流中“消失”。优先使用 handle 获取完整控制,用 exceptionally 提供默认值,用 whenComplete 做清理或日志。不复杂,但容易忽略。










