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

在Java中使用CompletableFuture进行异步编程时,异常处理是关键的一环。由于异步任务可能在后台线程中执行,未捕获的异常不会直接抛出到主线程,容易被忽略。因此,必须显式地处理异常,以确保程序的健壮性。
该方法用于在发生异常时提供一个备选结果,类似于 try-catch 中的 catch 块。
它接收一个函数,当原始 CompletableFuture 发生异常时,会调用这个函数,并返回一个新的 CompletableFuture。
CompletableFuture<String> future = 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
handle 比 exceptionally 更灵活,无论是否发生异常都会执行,接收两个参数:结果和异常。
立即学习“Java免费学习笔记(深入)”;
适用于需要根据结果或异常做不同处理的场景。
CompletableFuture<String> future = 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
如果在 thenApply 等链式操作中抛出异常,该异常也会被封装。可以在后续使用 exceptionally 或 handle 捕获。
CompletableFuture<Integer> future = 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
该方法用于副作用处理,比如日志记录或资源清理,不改变结果值。
它接收结果和异常,但返回的 CompletableFuture 仍保留原始的结果或异常。
CompletableFuture<String> future = 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 做清理或日志。不复杂,但容易忽略。
以上就是在Java中如何处理CompletableFuture异常的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号