3

Why in the code below "public void run() throws InterruptedException" creates a compilation error but "public void run() throws RuntimeException" does not?

The compilation error raised by InterruptedException is"Exception InterruptedException is not compatible with throws clause in Runnable.run()"

Is it because RuntimeException is unchecked exception therefore does not change the run() signature?

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

}

}

C graphics
  • 7,308
  • 19
  • 83
  • 134
  • 1
    "Is it because RuntimeException is unchecked exception therefore does not change the run() signature?" ... Yes. – Brian Roach Apr 10 '14 at 17:09
  • See also https://stackoverflow.com/questions/10513374/what-are-reasons-for-exceptions-not-to-be-compatible-with-throws-clauses – Raedwald Nov 05 '18 at 09:34

1 Answers1

7

The 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're overriding. However, RuntimeExceptions don't need to be declared, so they don't affect the throws clause. It's as if an implicit throws RuntimeException is already there.

The JLS, Section 8.4.8.3 states:

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thank you "When overriding a method, you cannot declare that it throws more checked exceptions than the method you're overriding" made it clear. – C graphics Apr 10 '14 at 17:11