Handle an exception thrown by a callable

In this post an example is provided to demonstrate how to handle an exception thrown by a Callable object.

Handle exception thrown by callable:

A few points to note from the above code.

  • A callable object which throws a RuntimeException, is passed into the submit() method.
  • The result of the callable object is retrieved by calling future.get()
  • The ExecutionException wraps the exception thrown by the callable object.
  • Invoking e.getCause() on the ExecutionException will return the RuntimeException.

Running the above code produces the following output:

I hope the example above, helps you understand how to get an exception thrown by a callable task.

Similar posts:

  1. How to use callable in Java
  2. How to create a Thread in Java
  3. Java WatchService example

References:

  1. ExecutionException API documentation
  2. Callable in Java

Leave a Reply