如何在使用 CompletableFuture.get() 时捕获 CompletableFuture.completeExceptionally() 抛出的异常?
这是一些代码
public CompletableFuture<Hello> sayHelloAsync() {
CompletableFuture<Hello> future = new CompletableFuture<>();
try{
sayHello(); //throws HelloException
} catch (HelloException ex) {
future.completeExceptionally(new MyException("hello exception"));
return future;
}
return future;
}
Now I want to do .get() or .join on this as follows
CompletableFuture<Hello> resultFuture = sayHelloAsync();
try{
result.get(); // throws ExecutionException but I want to catch My Exception in the simplest way possible but not by throwing another exception while catching the Execution exception and so on.
} catch(ExecutionException ex) {
throw ex.getCause();
} catch (MyException e) {
e.printStackTrace()
}
这是非常丑陋的。同样,我只想用尽可能少的代码行并以最简洁的方式捕获 MyException。不确定 isCompletedExceptionally() 是否异常,join() 可以帮助以最简单的方式捕获 MyException。如果有怎么办?