在下面的代码中,在匿名类实例化中编写的Thread.sleep(3000);
只能使用 try-catch 块进行处理。为什么 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()
内部定义的类中定义的。它们是两种不同的方法。
但是,不可能将 1 添加到run()
,因为Runnable
不允许run()
具有throws
子句。因此,唯一的解决方案是用 try/catch 块包裹sleep
。