考虑以下代码 -
public class TestCompletableFuture {
BiConsumer<Integer, Throwable> biConsumer = (x,y) -> {
System.out.println(x);
System.out.println(y);
};
public static void main(String args[]) {
TestCompletableFuture testF = new TestCompletableFuture();
testF.start();
}
public void start() {
Supplier<Integer> numberSupplier = new Supplier<Integer>() {
@Override
public Integer get() {
return SupplyNumbers.sendNumbers();
}
};
CompletableFuture<Integer> testFuture = CompletableFuture.supplyAsync(numberSupplier).whenComplete(biConsumer);
}
}
class SupplyNumbers {
public static Integer sendNumbers(){
return 25; // just for working sake its not correct.
}
}
Run Code Online (Sandbox Code Playgroud)
以上的事情很好.但是sendNumbers也可以在我的情况下抛出一个检查过的异常,例如:
class SupplyNumbers {
public …Run Code Online (Sandbox Code Playgroud) 使用Java 8很棒的功能CompletableFuture,我想使用此新功能的例外来转换旧的异步代码.但是经过检查的例外令我困扰.这是我的代码.
CompletableFuture<Void> asyncTaskCompletableFuture =
CompletableFuture.supplyAsync(t -> processor.process(taskParam));
Run Code Online (Sandbox Code Playgroud)
process方法签名:
public void process(Message msg) throws MyException;
Run Code Online (Sandbox Code Playgroud)
如何处理ComletableFuture中的已检查异常?
Stackoverflow 包含多个有关将检查异常与CompletableFuture.
这里有一些例子:
虽然一些答案暗示使用CompletableFuture.completeExceptionally()他们的方法会导致用户代码难以阅读。
我将利用这个空间提供一个替代解决方案,以提高可读性。
请注意,这个问题特定于 CompletableFuture。这使我们能够提供不更普遍地扩展到 lambda 表达式的解决方案。