Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why adding throws InterruptedException creates compilation error for implementation of Runnable [duplicate]

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

}

}

like image 463
C graphics Avatar asked Aug 23 '26 09:08

C graphics


1 Answers

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.

like image 57
rgettman Avatar answered Aug 25 '26 00:08

rgettman