面试题答案
一键面试在Java中,使用CompletableFuture
的supplyAsync
方法创建异步任务时,可以通过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();
}
}
}
在上述代码中:
CompletableFuture.supplyAsync
方法创建一个异步任务。- 在异步任务中,通过
Math.random()
模拟随机抛出异常。 - 使用
exceptionally
方法捕获异步任务中抛出的异常,并返回一个默认值。 - 使用
thenAccept
方法处理最终的结果(无论是正常结果还是异常处理后的默认值)。 - 同时,还展示了如何通过
get
方法获取最终结果,在获取结果时也需要处理InterruptedException
和ExecutionException
。