I used a static method supplyAsync() to get a CompletableFuture, and call its whenComplete() method to deal with the result and exception.
whenComplete() accepts a BiConsumer as parameter, and BiConsumer's second parameter is a Throwable. But I found that I can't throw a checked exception in supply() method. If I did, Idea will show a tip “Unhandled exception: java.lang.exception”.
public static void main(String[] args) {
Integer i = 0;
// unhandled exception
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> CompletableTest.getInt(i), executorService);
future.whenComplete((res, e) ->
{
System.out.println("res is " + res);
System.out.println("e is " + e);
});
}
public static Integer getInt(Integer i) throws Exception {
Thread.sleep(3000);
return i + 1;
}
I'm confused, whenComplete() can deal with checked exception, but I can't throw it.
Is it possible to throw a checked exception within CompletableFuture?