MST

星途 面试题库

面试题:Java中CompletableFuture如何使用exceptionally优雅捕获异常

请编写一段Java代码,展示如何使用CompletableFuture的exceptionally方法优雅地捕获异步操作中抛出的异常,并对异常进行处理,返回一个默认值。假设异步操作是模拟一个网络请求,例如从远程服务器获取数据。
32.6万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

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

public class CompletableFutureExceptionHandling {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟网络请求,这里可能抛出异常
            if (Math.random() < 0.5) {
                throw new RuntimeException("网络请求失败");
            }
            return "从远程服务器获取到的数据";
        });

        future.exceptionally(ex -> {
            System.out.println("捕获到异常: " + ex.getMessage());
            return "默认值";
        }).thenAccept(System.out::println);

        // 以下是获取结果的方式,在实际应用中如果需要阻塞获取结果可以使用这种方式
        try {
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}