在下面的代码中,Thread.sleep(3000);
编写在匿名类实例化内部的操作只能使用 try-catch block 来处理。为什么不throws InterruptedException
子句允许异常传播吗?
public static void main(String[] args) throws InterruptedException {
Runnable task = new Runnable() {
public void run() {
// below line explicitly need to be handled using try-catch. throws keyword does not work here
Thread.sleep(3000);
}
};
}
最佳答案
run()
方法缺少 throws InterruptedException
子句。 main()
是否有一个,以及 run()
是否在 main()
内部定义的类中定义都没有关系。它们是两种不同的方法。
不过,向 run()
添加 1 是不可能的,因为 Runnable
不允许 run()
有 抛出
子句。因此,唯一的解决方案是用 try/catch block 包装 sleep
。
关于java - 为什么 throws 关键字无法处理字段声明中抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48489973/