MST

星途 面试题库

面试题:Java中如何在流异步模式下处理异常

在Java流的异步操作模式中,当异步任务出现异常时,通常有哪些方式来捕获和处理这些异常?请举例说明。
36.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

在Java流的异步操作模式中,捕获和处理异常通常有以下几种方式:

  1. 使用handle方法handle方法可以同时处理正常结果和异常情况。
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        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);
    }
}
  1. 使用exceptionally方法exceptionally方法专门用于处理异常情况,并返回一个替代结果。
import java.util.concurrent.CompletableFuture;

public class Main {
    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);
    }
}
  1. 使用whenComplete方法whenComplete方法可以在任务完成(无论是正常完成还是异常完成)时执行一个回调,但不能改变返回结果。
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        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);
            }
        });
    }
}