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

前端 未结 9 1155
忘了有多久
忘了有多久 2020-12-07 14:43

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

相关标签:
9条回答
  • 2020-12-07 15:39

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

    0 讨论(0)
  • 2020-12-07 15:46

    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.

    0 讨论(0)
  • 2020-12-07 15:46

    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.

    0 讨论(0)
提交回复
热议问题