为什么添加throws InterruptedException会为Runnable的实现创建编译错误

时间:2014-04-10 17:05:56

标签: java multithreading exception

为什么在下面的代码中“public void run()throws InterruptedException ”会产生编译错误但是“public void run()抛出 RuntimeException ”不会?

InterruptedException引发的编译错误是“Exception InterruptedException与Runnable.run()中的throws子句不兼容”

是否因为RuntimeException是未经检查的异常,因此不会更改run()签名?

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

}

}

1 个答案:

答案 0 :(得分:7)

run() method as defined in the Runnable interface未列出任何throws子句中的任何异常,因此它只能抛出RuntimeException个。

覆盖方法时,您不能声明它会抛出比您覆盖的方法更多的已检查异常。但是,RuntimeException不需要声明,因此它们不会影响throws条款。好像隐含的throws RuntimeException已经存在。

JLS, Section 8.4.8.3州:

  

覆盖或隐藏另一个方法的方法(包括实现接口中定义的抽象方法的方法)可能不会被声明为抛出比重写或隐藏方法更多的已检查异常。