WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Expert · question 70 of 100

What is a CompletableFuture exceptionally() method in Java? How is it used?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, a CompletableFuture is a type of Future that represents a computation that may not yet be complete but will eventually produce a result. The exceptionally() method is used to handle exceptions that may occur during the execution of a CompletableFuture.

The exceptionally() method takes a function that is executed when an exception occurs during the execution of a CompletableFuture. The function takes the exception as a parameter and returns a new CompletableFuture. This allows you to recover from exceptions and continue processing the result.

Here’s an example that demonstrates the use of the exceptionally() method:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) 
    throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = 
            CompletableFuture.supplyAsync(() -> {
        if (Math.random() < 0.5) {
            throw new RuntimeException("Something went wrong");
        }
        return "Hello, World!";
        });
    
        future.exceptionally(ex -> {
            System.out.println("Exception occurred: " + ex.getMessage());
            return "Default Value";
        });
    
        System.out.println(future.get());
    }
}

In this example, a CompletableFuture is created using the supplyAsync() method. This method takes a supplier function that is executed asynchronously and returns a CompletableFuture. The supplier function randomly throws a RuntimeException to simulate an error.

The exceptionally() method is called on the CompletableFuture to handle the exception that may occur during the execution. In this case, it prints the exception message and returns a default value.

Finally, the result of the CompletableFuture is retrieved using the get() method, which will block until the computation is complete. If an exception occurs, the value returned by the exceptionally() method will be used instead of the original result.

Note that the exceptionally() method returns a new CompletableFuture that can be further chained with other CompletableFuture methods, such as thenApply(), thenAccept(), or thenRun().

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics