一、前言
在写代码时,经常需要对异常进行处理,最常用的就是try catch。
在用CompletableFuture编写多线程时,如果需要处理异常,可以用exceptionally,它的作用相当于catch。
exceptionally的特点:
- 当出现异常时,会触发回调方法exceptionally
- exceptionally中可指定默认返回结果,如果出现异常,则返回默认的返回结果
二、测试案例
public class Thread01_Exceptionally {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {
if (Math.random() < 0.5) {
throw new RuntimeException("抛出异常");
}
System.out.println("正常结束");
return 1.1;
}).thenApply(result -> {
System.out.println("thenApply接收到的参数 = " + result);
return result;
}).exceptionally(new Function<Throwable, Double>() {
@Override
public Double apply(Throwable throwable) {
System.out.println("异常:" + throwable.getMessage());
return 0.0;
}
});
System.out.println("最终返回的结果 = " + future.get());
}
}
当没有出现异常时结果:
正常结束
thenApply接收到的参数 = 1.1
最终返回的结果 = 1.1
当出现异常时结果:
异常:java.lang.RuntimeException: 抛出异常
最终返回的结果 = 0.0
从异常时结果可以看出,exceptionally中捕获了线程的异常信息。
future.get()获取了exceptionally返回的值0.0;
1124


异常处理 exceptionally&spm=1001.2101.3001.11974&articleId=116465133&d=1&t=3&u=8e5c3bf5f23648c69b02cd138bdc4f3c)

被折叠的 条评论
为什么被折叠?



