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

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


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


If you want to pass a class that implements Runnable into the Thread framework, then you have to play by that framework's rules, see Ernest Friedman-Hill's answer why doing it otherwise is a bad idea.

I have a hunch, though, that you want to call run method directly in your code, so your calling code can process the exception.

The answer to this problem is easy. Do not use Runnable interface from Thread library, but instead create your own interface with the modified signature that allows checked exception to be thrown, e.g.

public interface MyRunnable{    void myRun ( ) throws MyException;}

You may even create an adapter that converts this interface to real Runnable ( by handling checked exception ) suitable for use in Thread framework.


If run() threw a checked exception, what would catch it? There's no way for you to enclose that run() call in a handler, since you don't write the code that invokes it.

You can catch your checked exception in the run() method, and throw an unchekced exception (i.e., RuntimeException) in its place. This will terminate the thread with a stack trace; perhaps that's what you're after.

If instead you want your run() method to report the error somewhere, then you can just provide a callback method for the run() method's catch block to call; that method could store the exception object somewhere, and then your interested thread could find the object in that location.