MST

星途 面试题库

面试题:Java中CompletableFuture异常处理的常见方式

请描述在Java中使用CompletableFuture时,处理异常的两种常见方式,并分别给出简单示例代码。
37.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 使用exceptionally方法
    • exceptionally方法用于处理CompletableFuture中的异常。当CompletableFuture发生异常时,exceptionally方法中的回调函数会被执行,返回一个默认值或进行异常处理。
    • 示例代码:
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExceptionHandling {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            if (Math.random() > 0.5) {
                throw new RuntimeException("Simulated exception");
            }
            return "Success result";
        })
       .exceptionally(ex -> {
            System.out.println("Caught exception: " + ex.getMessage());
            return "Default value";
        })
       .thenAccept(System.out::println);
    }
}
  1. 使用whenComplete方法
    • whenComplete方法会在CompletableFuture完成(无论是正常完成还是异常完成)时执行。它接收两个参数,第一个是正常完成时的结果(如果有异常则为null),第二个是异常(如果正常完成则为null)。
    • 示例代码:
import java.util.concurrent.CompletableFuture;

public class CompletableFutureExceptionHandling2 {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> {
            if (Math.random() > 0.5) {
                throw new RuntimeException("Simulated exception");
            }
            return "Success result";
        })
       .whenComplete((result, ex) -> {
            if (ex != null) {
                System.out.println("Caught exception: " + ex.getMessage());
            } else {
                System.out.println("Result: " + result);
            }
        });
    }
}