加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么添加throws InterruptedException会为Runnable的

发布时间:2020-12-15 04:19:24 所属栏目:Java 来源:网络整理
导读:参见英文答案 Is there a way to make Runnable’s run() throw an exception?????????????????????????????????????9个 为什么在下面的代码“public void run()throws InterruptedException”创建一个编译错误,但“public void run()抛出RuntimeException”
参见英文答案 > Is there a way to make Runnable’s run() throw an exception?????????????????????????????????????9个
为什么在下面的代码“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() method as defined in the Runnable interface没有在任何throws子句中列出任何异常,因此它只能抛出RuntimeExceptions.

覆盖方法时,您不能声明它会抛出比您覆盖的方法更多的已检查异常.但是,不需要声明RuntimeExceptions,因此它们不会影响throws子句.这就好像隐式抛出RuntimeException已经存在.

JLS,Section 8.4.8.3指出:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读