【发布时间】:2020-11-24 13:25:21
【问题描述】:
问题很简单:我正在寻找一种优雅的方式来使用CompletableFuture#exceptionally 和CompletableFuture#supplyAsync。这是行不通的:
private void doesNotCompile() {
CompletableFuture<String> sad = CompletableFuture
.supplyAsync(() -> throwSomething())
.exceptionally(Throwable::getMessage);
}
private String throwSomething() throws Exception {
throw new Exception();
}
我认为exceptionally() 背后的想法正是为了处理抛出Exception 的情况。但是,如果我这样做,它会起作用:
private void compiles() {
CompletableFuture<String> thisIsFine = CompletableFuture.supplyAsync(() -> {
try {
throwSomething();
return "";
} catch (Exception e) {
throw new RuntimeException(e);
}
}).exceptionally(Throwable::getMessage);
}
我可以使用它,但它看起来很糟糕并且使事情更难维护。有没有不需要将所有Exception 转换为RuntimeException 的方法来保持这种清洁?
【问题讨论】:
-
如果要使用第一个选项,只需将
throwSomething()的返回类型从void更改为String即可。 -
对不起,这是我在写这个简化版本时的一个错误。我根据您的建议编辑了 OP,指出它不能解决问题。
-
啊,对不起。我忘了你在处理 checked 异常。基本上,问题是
Supplier#get()没有声明为抛出Exception。也许这里的东西会对你有所帮助:Java 8 Lambda function that throws exception?.
标签: java exception completable-future