|
|
@@ -0,0 +1,41 @@
|
|
|
+package space.anyi;
|
|
|
+
|
|
|
+import java.util.concurrent.CompletableFuture;
|
|
|
+
|
|
|
+public class Cf07_ExceptionHandling {
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
+ // exceptionally: 任务失败时给出降级结果(类似异常被"恢复")
|
|
|
+ CompletableFuture<Integer> fallback = failTask().exceptionally(e -> {
|
|
|
+ System.out.println("exceptionally 捕获: " + e.getClass().getSimpleName());
|
|
|
+ return -1; // 降级返回
|
|
|
+ });
|
|
|
+ System.out.println("exceptionally 降级结果: " + fallback.join());
|
|
|
+
|
|
|
+ // whenComplete: 只"观察"结果或异常,做了日志记录就够,
|
|
|
+ // 注意它不消化异常 —— 原任务失败,链上的 join/get 依然会抛 CompletionException
|
|
|
+ CompletableFuture<Integer> observed = failTask();
|
|
|
+ try {
|
|
|
+ observed.whenComplete((res, ex) -> {
|
|
|
+ if (ex != null) {
|
|
|
+ System.out.println("whenComplete 观察到异常: " + ex.getClass().getSimpleName());
|
|
|
+ } else {
|
|
|
+ System.out.println("whenComplete 观察到结果: " + res);
|
|
|
+ }
|
|
|
+ }).join();
|
|
|
+ } catch (Exception e) {
|
|
|
+ System.out.println("whenComplete 不吞异常, join() 抛: " + e.getClass().getSimpleName());
|
|
|
+ }
|
|
|
+
|
|
|
+ // handle: 无论成功失败都给一个函数处理,并可返回新结果(可恢复)
|
|
|
+ CompletableFuture<String> handled = failTask().handle((res, ex) ->
|
|
|
+ ex == null ? "正常结果: " + res : "出错被恢复: " + ex.getMessage());
|
|
|
+ System.out.println("handle 结果: " + handled.join());
|
|
|
+ }
|
|
|
+
|
|
|
+ private static CompletableFuture<Integer> failTask() {
|
|
|
+ return CompletableFuture.supplyAsync(() -> {
|
|
|
+ System.out.println("任务执行中...");
|
|
|
+ throw new RuntimeException("模拟异常");
|
|
|
+ });
|
|
|
+ }
|
|
|
+}
|