Search⌘ K
AI Features

ExecutionException

Explore the ExecutionException in Java concurrency which arises when a FutureTask encounters an unhandled exception or error. Understand how retrieving a failed task's result triggers this exception and learn proper exception handling techniques to avoid programming errors in concurrent environments.

We'll cover the following...

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

Overview

ExecutionException is a checked exception that extends the Exception class. This exception is thrown by an instance of FutureTask that encounters an Exception or Error (both derivates of Throwable) that remain unhandled by user code and, subsequently an attempt is made to retrieve the result of such a task.

Example

Consider the program below that has a task submitted to the ExecutorService. The task simply throws a runtime exception to simulate failure. When we attempt to retrieve the result of the task, the snippet futureTask.get() throws ExecutionException.

Java
import java.util.concurrent.*;
class Demonstration {
public static void main( String args[] ) {
ExecutorService es = Executors.newFixedThreadPool(5);
// Create a FutureTask, which takes in an instance of Callable
FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// The task simulates encountering an exception by throwing one.
throw new RuntimeException("runtime issue");
}
});
try {
es.submit(futureTask);
// wait a while for the task
Thread.sleep(300);
// Attempt to get the result of the task
futureTask.get();
} catch (ExecutionException e) {
// You should see the following line print in the console.
System.out.println("ExceutionException thrown by program.");
} catch (InterruptedException ie) {
// we can ignore InterruptedException for demo purposes
} finally {
// remember to shutdown the executor service
es.shutdown();
}
}
}

In the above example, if you comment out line#23 and the associated catch clause for ExecutionException, upon re-run of the program you’ll notice that it doesn’t throw ExecutionException even though the task throws a runtime exception. A programming oversight to retrieve the result of submitted task that fail can falsely lead the program to exit successfully.

Finally, if we replace line#12 with the snippet throw new Error();, we’ll still observe the ExecutionException being throw upon retrieving the result of the program.