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

10

97

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?

Isopropanol answered 20/7, 2012 at 17:25 Comment(2)
In addition to other answers, to track progress of task, you can use FutureTask class.Uganda
Non-android Java question: #1369704Particularize
A
44

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.

Arella answered 20/7, 2012 at 17:36 Comment(2)
Such a simple solution arrived at just by not thinking "in the box". Of course, a Runnable is just a simple interface and we can make our own. Not useful for the thread use-case but for passing different "runnable" chunks of code around this is perfect.Gride
That means we have to create another MyTimerTask or MyThread to use MyRunable ....Gaidano
H
96

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

Henryk answered 20/7, 2012 at 17:32 Comment(0)
A
44

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.

Arella answered 20/7, 2012 at 17:36 Comment(2)
Such a simple solution arrived at just by not thinking "in the box". Of course, a Runnable is just a simple interface and we can make our own. Not useful for the thread use-case but for passing different "runnable" chunks of code around this is perfect.Gride
That means we have to create another MyTimerTask or MyThread to use MyRunable ....Gaidano
L
28

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.

Leman answered 20/7, 2012 at 17:28 Comment(1)
The first part is not a good argument. "If main() threw a checked exception, what would catch it?" "If run() threw an unchecked exception, what would catch it?"Conveyancer
G
24

Yes, there is a way to throw a checked exception from the run() method, but it's so terrible I won't share it.

Here's what you can do instead; it uses the same mechanism that a runtime exception would exercise:

@Override
public void run() {
  try {
    /* Do your thing. */
    ...
  } catch (Exception ex) {
    Thread t = Thread.currentThread();
    t.getUncaughtExceptionHandler().uncaughtException(t, ex);
  }
}

As others have noted, if your run() method is really the target of a Thread, there's no point in throwing an exception because it is unobservable; throwing an exception has the same effect as not throwing an exception (none).

If it's not a Thread target, don't use Runnable. For example, perhaps Callable is a better fit.

Gourmandise answered 20/7, 2012 at 17:34 Comment(6)
But does this cause the process to crash when it throws??Propraetor
@DineshVG No, only a bug in the JVM can cause a true crash. The default exception handler just prints the exception. If you are used to seeing the process exit after that, it's because that thread was the only thread running, and it terminated.Gourmandise
I tried (in android instrumentation test cases) using this for a soap call, where if I get a 400 from Soap call, I throw an exception. This soap call is called from a thread while starting the test case. This thread uses this t.getUncaughtExceptionHandler().uncaughtException(t, ex); to throw it to the instrumentation test case. Adding this one line causes the process to crash!. Don't know why.Propraetor
@DineshVG In that environment, does Thread.getDefaultUncaughtExceptionHandler() return null? If not, what is the type of the result? What happens if, instead of calling uncaughtException(), you wrap the checked exception in a RuntimeException and throw that?Gourmandise
RuntimeException also causes the application to crash.Propraetor
@DineshVG Android may be setting a default uncaught exception handler that does this. That's why I asked if Thread.getDefaultUncaughtExceptionHandler() returns null; if not, Android is providing a default, in order to offer reporting, etc. But you can set it to do what you want. There's more info here.Gourmandise
R
14
@FunctionalInterface
public interface CheckedRunnable<E extends Exception> extends Runnable {

    @Override
    default void run() throws RuntimeException {
        try {
            runThrows();
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    void runThrows() throws E;

}
Redwood answered 20/11, 2018 at 17:7 Comment(0)
C
6

Some people try to convince you that you have to play by the rules. Listen, but whether you obey, you should decide yourself depending on your situation. The reality is "you SHOULD play by the rules" (not "you MUST play by the rules"). Just be aware that if you do not play by the rules, there might be consequences.

The situation not only applies in the situation of Runnable, but with Java 8 also very frequently in the context of Streams and other places where functional interfaces have been introduced without the possibility to deal with checked exceptions. For example, Consumer, Supplier, Function, BiFunction and so on have all been declared without facilities to deal with checked exceptions.

So what are the situations and options? In the below text, Runnable is representative of any functional interface that doesn't declare exceptions, or declares exceptions too limited for the use case at hand.

  1. You've declared Runnable somewhere yourself, and could replace Runnable with something else.
    1. Consider replacing Runnable with Callable<Void>. Basically the same thing, but allowed to throw exceptions; and has to return null in the end, which is a mild annoyance.
    2. Consider replacing Runnable with your own custom @FunctionalInterface that can throw exactly those exceptions that you want.
  2. You've used an API, and alternatives are available. For example, some Java APIs are overloaded so you could use Callable<Void> instead of Runnable.
  3. You've used an API, and there are no alternatives. In that case, you're still not out of options.
    1. You can wrap the exception in RuntimeException.
    2. You can hack the exception into a RuntimeException by using an unchecked cast.

You can try the following. It's a bit of a hack, but sometimes a hack is what we need. Because, whether an exception should be checked or unchecked is defined by its type, but practically should actually be defined by the situation.

@FunctionalInterface
public interface ThrowingRunnable extends Runnable {
    @Override
    default void run() {
        try {
            tryRun();
        } catch (final Throwable t) {
            throwUnchecked(t);
        }
    }

    private static <E extends RuntimeException> void throwUnchecked(Throwable t) {
        throw (E) t;
    }

    void tryRun() throws Throwable;
}

I prefer this over new RuntimeException(t) because it has a shorter stack trace.

You can now do:

executorService.submit((ThrowingRunnable) () -> {throw new Exception()});

Disclaimer: The ability to perform unchecked casts in this way might actually be removed in future versions of Java, when generics type information is processed not only at compile time, but also at runtime.

Conveyancer answered 24/11, 2018 at 8:52 Comment(0)
E
0

Your requirement doesn't make any sense. If you want to notify the called of the thread about an exception that happened, you could do that through a call back mechanism. This can be through a Handler or a broadcast or whatever else you can think of.

Enteritis answered 20/7, 2012 at 17:29 Comment(0)
G
0

I think a listener pattern might help you with this scenario. In case of an exception happening in your run() method, use a try-catch block and in the catch send a notification of an exception event. And then handle your notification event. I think this would be a cleaner approach. This SO link gives you a helpful pointer to that direction.

Gaynell answered 20/7, 2012 at 17:32 Comment(0)
D
0

Yes, you can throw checked exceptions from the run() method. It can be done with generics by tricking the compiler. Look at this code:

public static void main(String[] args) {

    new Main().throwException();

}

public void throwException() {
    Runnable runnable = () -> throwAs(new Exception());

    new Thread(runnable).start();
}

private  <T extends Throwable> void throwAs(Throwable t) throws T {
    throw ( T ) t;
}

This might be helpful if you want to throw checked exceptions from the run() method of Runnable

Disconnection answered 21/1, 2023 at 14:12 Comment(0)
M
-1

The easiest way is to define your own exception object which extend the RuntimeException class instead of the Exception class.

Milan answered 15/3, 2016 at 3:2 Comment(2)
And how would you get hold of this RuntimeException when it occurs my dear sir?Royster
That alone doesn't answer the question.Badmouth

© 2022 - 2025 — McMap. All rights reserved.