java – 为什么添加throws InterruptedException会为Runnable的
参见英文答案 >
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指出:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |