Java – why does adding throws interruptedexception create compilation errors for the implementation of runnable
Is there a way to make runnable's run() throw an exception? 9
The compilation error caused by interruptedexception is "exception interruptedexception is incompatible with the throws clause in runnable. Run()"
Is it because runtimeException is an unchecked exception, so the run () signature will not be changed?
public class MyThread implements Runnable{ String name; public MyThread(String name){ this.name = name; } @Override public void run() throws RuntimeException{ for (int i = 0; i < 10; i++) { try { Thread.sleep(Math.round(100*Math.random())); System.out.println(i+" "+name); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { Thread thread1 = new Thread (new MyThread("Jay")); Thread thread2 = new Thread (new MyThread("John")); thread1.start(); thread2.start(); }
}
Solution
Run () method as defined in the runnable interface does not list any exceptions in any throws clause, so it can only throw runtimeexceptions
When overriding a method, you cannot declare that it throws more checked exceptions than the method you override However, runtimeexceptions do not need to be declared, so they do not affect the throws clause It's like implicitly throwing a runtimeException that already exists
JLS,Section 8.4. 8.3 state:
A method that overrides or hides another method,including methods that implement abstract methods defined in interfaces,may not be declared to throw more checked exceptions than the overridden or hidden method.