Is there a way to make Runnable's run() throw an exception?

Regex Rookie picture Regex Rookie · Jul 20, 2012 · Viewed 75.6k times · Source

A method I am calling in run() in a class that implements Runnable) is designed to be throwing an exception.

But the Java compiler won't let me do that and suggests that I surround it with try/catch.

The problem is that by surrounding it with a try/catch I make that particular run() useless. I do want to throw that exception.

If I specify throws for run() itself, the compiler complains that Exception is not compatible with throws clause in Runnable.run().

Ordinarily I'm totally fine with not letting run() throw an exception. But I have unique situation in which I must have that functionality.

How to I work around this limitation?

Answer

Alexander Kulyakhtin picture Alexander Kulyakhtin · Jul 20, 2012

You can use a Callable instead, submitting it to an ExecutorService and waiting for result with FutureTask.isDone() returned by the ExecutorService.submit().

When isDone() returns true you call FutureTask.get(). Now, if your Callable has thrown an Exception then FutureTask.get() wiill throw an Exception too and the original Exception you will be able to access using Exception.getCause().