前言
在写代码时,经常需要对异常进行处理,最常用的就是 try catch。
在用 CompletableFuture 编写多线程时,如果需要处理异常,可以用 exceptionally,它的作用相当于 catch。
exceptionally 的特点:
当出现异常时,会触发回调方法 exceptionally
exceptionally 中可指定默认返回结果,如果出现异常,则返回默认的返回结果
1 | public class Thread01_Exceptionally { |
// final Stream<CompletableFuture
// CompletableFuture.supplyAsync(() -> {
// throw new RuntimeException(“抛出异常”);
// }),
// CompletableFuture.supplyAsync(() -> {
// return “future2”;
// })
// );
//
// final List
//
// return stream.map(future -> {
// try {
// return future.get();
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }).collect(Collectors.toList());
// }).get();
//
//
// System.out.println(strings);