Saturday, September 24, 2011

Throw an exception from a Java thread and handle it on the parent thread

Let say you want to compute a result in the background of a program. Usually it's achieved by encapsulate the task inside a Runnable object and run it in a new thread. If an error occurs during the process you want your program to be notified and handle errors. But unfortunately the run() method of the Runnable interface doesn't allow to throw exceptions.

In this post I will demonstrate a way to achieved that based on Callable and Executors.