MST

星途 面试题库

面试题:Java CompletableFuture异常处理链的构建与应用

假设你有一系列通过CompletableFuture链接的异步任务,当前一个任务出现异常时,如何构建异常处理链,使得后续任务能够根据异常类型进行不同的处理,并继续执行其他正常的任务分支?请编写代码示例。
33.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExceptionHandling {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            // 模拟可能抛出异常的任务
            if (Math.random() < 0.5) {
                throw new RuntimeException("Specific Exception");
            }
            return "Task 1 completed";
        })
       .handle((result, ex) -> {
            if (ex != null) {
                if (ex instanceof RuntimeException && "Specific Exception".equals(ex.getMessage())) {
                    System.out.println("Handling specific exception: " + ex.getMessage());
                    return "Recovered from specific exception";
                } else {
                    System.out.println("Handling other exception: " + ex.getMessage());
                    return "Recovered from other exception";
                }
            }
            return result;
        })
       .thenApply(result -> {
            System.out.println("Task 2 processing: " + result);
            return result + " -> Task 2";
        })
       .thenAccept(System.out::println);

        // 等待所有任务完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中:

  1. CompletableFuture.supplyAsync 模拟了一个可能抛出异常的异步任务。
  2. handle 方法用于处理前一个任务可能抛出的异常。在 handle 方法中,根据异常类型进行不同的处理,并返回相应的恢复结果。
  3. thenApplythenAccept 等方法继续执行后续的任务分支,即使前一个任务出现异常,经过 handle 处理后,后续任务也能正常执行。