如何在使用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。如果是这样的话?