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.
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.
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.