为什么在下面的代码中“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();
}
}
答案 0 :(得分:7)
run()
method as defined in the Runnable
interface未列出任何throws
子句中的任何异常,因此它只能抛出RuntimeException
个。
覆盖方法时,您不能声明它会抛出比您覆盖的方法更多的已检查异常。但是,RuntimeException
不需要声明,因此它们不会影响throws
条款。好像隐含的throws RuntimeException
已经存在。
覆盖或隐藏另一个方法的方法(包括实现接口中定义的抽象方法的方法)可能不会被声明为抛出比重写或隐藏方法更多的已检查异常。