MST
星途 面试题库

面试题:Java中CompletableFuture的supplyAsync方法创建异步任务时如何处理异常

在使用Java的CompletableFuture的supplyAsync方法创建异步任务时,假设异步任务中可能会抛出异常,你该如何捕获并处理这个异常?请给出代码示例说明。
20.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

在Java中,使用CompletableFuturesupplyAsync方法创建异步任务时,可以通过exceptionally方法来捕获并处理异常。以下是代码示例:

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("模拟异常");
            }
            return "任务正常完成";
        })
       .exceptionally(ex -> {
            System.out.println("捕获到异常: " + ex.getMessage());
            return "默认值";
        })
       .thenAccept(System.out::println);

        // 如果需要获取最终结果,可以使用get方法
        try {
            String result = CompletableFuture.supplyAsync(() -> {
                if (Math.random() < 0.5) {
                    throw new RuntimeException("模拟异常");
                }
                return "任务正常完成";
            })
           .exceptionally(ex -> {
                System.out.println("捕获到异常: " + ex.getMessage());
                return "默认值";
            })
           .get();
            System.out.println("最终结果: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中:

  1. CompletableFuture.supplyAsync方法创建一个异步任务。
  2. 在异步任务中,通过Math.random()模拟随机抛出异常。
  3. 使用exceptionally方法捕获异步任务中抛出的异常,并返回一个默认值。
  4. 使用thenAccept方法处理最终的结果(无论是正常结果还是异常处理后的默认值)。
  5. 同时,还展示了如何通过get方法获取最终结果,在获取结果时也需要处理InterruptedExceptionExecutionException