1、whenComplete ()
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Oops!");
});
CompletableFuture<String> result = future.thenApply(i -> "Success: " + i)
.whenComplete((res, ex) -> {
if (ex != null) {
System.out.println("Error occurred: " + ex);
}
});
result.join(); // 此处会输出错误信息
2、exceptionly ()
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Oops!");
});
CompletableFuture<String> result = future.thenApply(i -> "Success: " + i)
.exceptionally(ex -> {
System.out.println("Error occurred: " + ex);
throw new RuntimeException("Error occurred: " + ex);
});
result.join(); // 此处会抛出重新抛出的异常
3、Handle ()
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Oops!");
});
CompletableFuture<String> result = future.handle((res, ex) -> {
if (ex != null) {
System.out.println("Error occurred: " + ex);
return "Default Value";
} else {
return "Success: " + res;
}
});
result.join(); // 此处会返回默认值
join()和get()的异同:
- join()和get()方法都是用来获取CompletableFuture异步之后的返回值
- join()方法抛出的是uncheck异常(即RuntimeException),不会强制开发者抛出,会将异常包装成CompletionException异常 /CancellationException异常,但是本质原因还是代码内存在的真正的异常,
- get()方法抛出的是经过检查的异常,ExecutionException, InterruptedException 需要用户手动处理(抛出或者 try catch)