C g*_*ics 3 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();
}
Run Code Online (Sandbox Code Playgroud)
}
接口中run()定义Runnable的方法不会列出任何子throws句中的任何异常,因此它只能抛出RuntimeExceptions.
覆盖方法时,您不能声明它会抛出比您覆盖的方法更多的已检查异常.但是,RuntimeException不需要声明s,因此它们不会影响该throws子句.就好像隐含throws RuntimeException已经存在一样.
在JLS,第8.4.8.3规定:
覆盖或隐藏另一个方法的方法(包括实现接口中定义的抽象方法的方法)可能不会被声明为抛出比重写或隐藏方法更多的已检查异常.
| 归档时间: |
|
| 查看次数: |
908 次 |
| 最近记录: |