1

In the code below, Thread.sleep(3000); written inside the anonymous class instantiation can be handled only using a try-catch block. Why doesn't the throws InterruptedException clause allow the exception to propagate?

public static void main(String[] args) throws InterruptedException {
    Runnable task = new Runnable() {
        public void run() {
            // below line explicitly need to be handled using try-catch. throws keyword does not work here
            Thread.sleep(3000);         
        }
    };
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
S Kumar
  • 555
  • 7
  • 21
  • 1
    This has nothing to do with field declaration. Try putting the `Runnable task = ...` inside a method: you will get exactly the same error. – Andy Turner Jan 28 '18 at 18:45

1 Answers1

2

The run() method lacks a throws InterruptedException clause. It doesn't matter that main() has one, nor that run() is defined in an class defined inside of main(). They're two different methods.

Adding one to run() isn't possible, though, because Runnable doesn't allow run() to have a throws clause. Therefore, the only solution is to wrap the sleep with a try/catch block.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Same answer. The nesting doesn't matter. – John Kugelman Jan 28 '18 at 19:12
  • So, that means inside the anonymous inner class, an exception can be handled only using the try-catch block. – S Kumar Jan 28 '18 at 19:21
  • 1
    @SKumar no: a *checked* exception must always be handled, either with try/catch or with a `throws` declaration on the method. You can't add a `throws` declaration to a method that is not covariant with any of the `throws` declaration of that it is overriding. `Runnable.run()` implicitly `throws RuntimeException, Error`; `InterruptedException` is covariant with neither, so you can't add `throws InterruptedException`. Therefore, you have to use try/catch. If your anonymous class were e.g. `Callable`, you could use `throws`, because `Callable.call()` throws `Exception`. – Andy Turner Jan 28 '18 at 19:49