CompletionException

Guide to understanding CompletionException

We'll cover the following

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The CompletionException extends from the RuntimeException and is thrown when a task hits an error or exception when executing.

The CompletionException and the ExecutionException might seem similar but there’s a fundamental difference between the two. The ExecutionException is thrown only when an attempt is made to retrieve the result/outcome of a task, while the CompletionException can be thrown when waiting on a task to complete or when trying to retrieve a result computed by a task. In a sense CompletionException can be thought of as broader in scope than ExecutionException.

Example

We’ll use the CompletableFuture class to demonstrate the CompletionException. The CompletableFuture class is used to program asynchronously in Java. It exposes a method completeExceptionally that takes in an instance of Throwable to indicate the failure experienced by the task. When the main thread attempts to wait for the task to complete by invoking the join() method the CompletionException is thrown.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy