LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 7

handle() sees both result and error Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    static String describe(int divisor) {
        return CompletableFuture.supplyAsync(() -> 100 / divisor)
            .handle((value, ex) -> ex == null ? "ok " + value : "failed (" + ex.getCause().getClass().getSimpleName() + ")")
            .join();
    }

    public static void main(String[] args) {
        System.out.println(describe(4) + " | " + describe(0));
    }
}
  • A ok 25 | failed (ArithmeticException) Correct
  • B ok 25 | failed (CompletionException)
  • C ok 25 | ok 0
  • D CompletionException
Correct Answer: Option A

handle always runs; the exception from supplyAsync arrives wrapped in a CompletionException, whose cause is the real error.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links