MST

星途 面试题库

面试题:Java中CompletableFuture异步任务执行错误恢复基础

请简述在Java中,CompletableFuture如何捕获并处理异步任务执行过程中抛出的异常,写出关键代码示例。
48.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

在Java中,CompletableFuture 可以通过以下几种方式捕获并处理异步任务执行过程中抛出的异常:

  1. 使用 exceptionally 方法exceptionally 方法用于处理 CompletableFuture 执行过程中抛出的异常,并返回一个新的 CompletableFuture,这个新的 CompletableFuture 的结果是处理异常后的结果。

    CompletableFuture.supplyAsync(() -> {
        if (Math.random() > 0.5) {
            throw new RuntimeException("模拟异常");
        }
        return "任务正常执行结果";
    }).exceptionally(ex -> {
        System.err.println("捕获到异常: " + ex.getMessage());
        return "异常处理后的默认结果";
    }).thenAccept(System.out::println);
    
  2. 使用 whenComplete 方法whenComplete 方法会在 CompletableFuture 执行完成(无论是正常完成还是异常完成)时执行,它接收两个参数,第一个是正常的结果(如果有异常则为 null),第二个是异常(如果正常完成则为 null)。

    CompletableFuture.supplyAsync(() -> {
        if (Math.random() > 0.5) {
            throw new RuntimeException("模拟异常");
        }
        return "任务正常执行结果";
    }).whenComplete((result, ex) -> {
        if (ex != null) {
            System.err.println("捕获到异常: " + ex.getMessage());
        } else {
            System.out.println("任务正常执行结果: " + result);
        }
    });
    
  3. 使用 handle 方法handle 方法结合了 whenCompletethenApply 的功能,它在 CompletableFuture 执行完成(正常或异常)时执行,并返回一个新的 CompletableFuture,新的 CompletableFuture 的结果由 handle 方法的返回值决定。

    CompletableFuture.supplyAsync(() -> {
        if (Math.random() > 0.5) {
            throw new RuntimeException("模拟异常");
        }
        return "任务正常执行结果";
    }).handle((result, ex) -> {
        if (ex != null) {
            System.err.println("捕获到异常: " + ex.getMessage());
            return "异常处理后的默认结果";
        } else {
            return result;
        }
    }).thenAccept(System.out::println);