MST

星途 面试题库

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

在Java的CompletableFuture中,列举至少两种常见的异常处理方式,并简要说明它们的适用场景及使用方法。
11.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 使用exceptionally方法
    • 适用场景:适用于当CompletableFuture出现异常时,希望返回一个默认值或者对异常进行简单处理并返回一个替代结果的场景。
    • 使用方法:在CompletableFuture对象调用exceptionally方法,方法接收一个Function参数,该Function的输入为Throwable(即异常),返回值为替代结果。例如:
    CompletableFuture.supplyAsync(() -> {
        if (Math.random() < 0.5) {
            throw new RuntimeException("模拟异常");
        }
        return "正常结果";
    }).exceptionally(ex -> {
        System.out.println("捕获到异常: " + ex.getMessage());
        return "默认结果";
    }).thenAccept(System.out::println);
    
  2. 使用handle方法
    • 适用场景:适用于无论CompletableFuture是正常完成还是异常完成,都需要对结果(正常结果或异常情况下的特殊处理)进行统一处理的场景。
    • 使用方法:在CompletableFuture对象调用handle方法,方法接收一个BiFunction参数,第一个参数为正常结果(如果有异常则为null),第二个参数为异常(如果正常完成则为null),返回值为最终处理后的结果。例如:
    CompletableFuture.supplyAsync(() -> {
        if (Math.random() < 0.5) {
            throw new RuntimeException("模拟异常");
        }
        return "正常结果";
    }).handle((result, ex) -> {
        if (ex != null) {
            System.out.println("捕获到异常: " + ex.getMessage());
            return "异常处理结果";
        }
        return result;
    }).thenAccept(System.out::println);
    
  3. 使用whenComplete方法
    • 适用场景:适用于只想在CompletableFuture完成(正常或异常)时执行一些操作,而不改变最终结果的场景。例如记录日志等。
    • 使用方法:在CompletableFuture对象调用whenComplete方法,方法接收一个BiConsumer参数,第一个参数为正常结果(如果有异常则为null),第二个参数为异常(如果正常完成则为null)。例如:
    CompletableFuture.supplyAsync(() -> {
        if (Math.random() < 0.5) {
            throw new RuntimeException("模拟异常");
        }
        return "正常结果";
    }).whenComplete((result, ex) -> {
        if (ex != null) {
            System.out.println("捕获到异常: " + ex.getMessage());
        } else {
            System.out.println("正常结果: " + result);
        }
    }).thenApply(result -> {
        // 这里的result不受whenComplete影响
        return result == null? "默认值" : result;
    }).thenAccept(System.out::println);