1

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?

Didier L
  • 18,905
  • 10
  • 61
  • 103
lulijun
  • 415
  • 3
  • 22
  • 2
    Possible duplicate of [Checked exception with CompletableFuture](https://stackoverflow.com/questions/39340239/checked-exception-with-completablefuture) – default locale Aug 09 '18 at 04:13
  • 1
    Other candidates: https://stackoverflow.com/questions/28959849/java-8-supplier-exception-handling/28961083#28961083 https://stackoverflow.com/questions/23184964/jdk8-completablefuture-supplyasync-how-to-deal-with-interruptedexception https://stackoverflow.com/questions/18198176/java-8-lambda-function-that-throws-exception – default locale Aug 09 '18 at 04:14
  • Possible duplicate of [Java 8 Supplier Exception handling](https://stackoverflow.com/questions/28959849/java-8-supplier-exception-handling) – Didier L Aug 09 '18 at 23:08

0 Answers0