What is CompletableFuture.completeExceptionally() in Java?

Overview

completeExceptionally() is an instance method of the CompletableFuture which is used to complete the futurerepresents the result of an asynchronous computation with the given exception. The subsequent calls to methods where we can retrieve results like get() and join() throwing the given exception.

The completeExceptionally method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, we check the following import statement.

import java.util.concurrent.CompletableFuture;

Syntax


public boolean completeExceptionally(Throwable ex)

Parameters

  • Throwable ex: The exception to throw.

Return value

This method returns true if the method call resulted in the transition of the CompletableFuture to a completed state. Otherwise, it returns false.

Code

Let’s take a look at the code.

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
CompletableFuture<Integer> completableFuture = new CompletableFuture<>();
RuntimeException runtimeException = new RuntimeException("Runtime Exception");
boolean flag = completableFuture.completeExceptionally(runtimeException);
if(flag) System.out.println("Future moved to completed stage");
if(completableFuture.isCompletedExceptionally()) System.out.println("Future completed exceptionally");
Integer result = null;
try {
result = completableFuture.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println("Exception while getting the result of the future. " + e.getMessage());
}
System.out.println("Result - " + result);
}
}

Explanation

  • Line 1: We import the classes in the concurrent package.
  • Line 5: We create an instance of CompletableFuture that is incomplete using the constructor of the CompletableFuture class.
  • Line 6: We define the exception to be thrown.
  • Line 7: We use the completeExceptionally() method, the future created in line 5 is moved to the completed stage with the exception defined in line 6. The completeExceptionally() method returns a Boolean that’s stored in the flag variable.
  • Line 8: Depending on the flag value, we print whether the future was moved to the completed stage or not.
  • Line 9: Using the isCompletedExceptionally(), we check whether the future was completed exceptionally or not.
  • Line 10: We retrieve the value of the future using the get() method. At this point, the exception defined in line 6 is thrown and caught in the catch block.
  • Line 11: The result will remain null as initialized and null will be printed to the console.

Free Resources