MST

星途 面试题库

面试题:Java CompletableFuture handle在复杂异步任务链中的异常处理与新结果返回

假设有一个包含多个CompletableFuture的异步任务链,每个任务依赖前一个任务的结果。其中某个任务可能会抛出特定类型的异常,要求在异常发生时,使用handle方法处理异常,并根据异常类型返回不同的新结果,同时保证任务链后续任务能够正确执行。请编写相应的Java代码实现该场景。
36.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

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

public class CompletableFutureExceptionHandling {

    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            // 模拟第一个异步任务
            return "Initial Result";
        })
       .thenApply(result -> {
            // 模拟第二个异步任务,可能抛出异常
            if ("Initial Result".equals(result)) {
                throw new CustomException("Custom Exception Occurred");
            }
            return result + " processed";
        })
       .handle((result, ex) -> {
            if (ex != null) {
                if (ex instanceof CustomException) {
                    return "Result for Custom Exception";
                } else {
                    return "Result for other Exceptions";
                }
            }
            return result;
        })
       .thenApply(finalResult -> {
            // 后续任务继续执行
            return "Final processing: " + finalResult;
        })
       .thenAccept(System.out::println);
    }

    static class CustomException extends RuntimeException {
        public CustomException(String message) {
            super(message);
        }
    }
}