为什么抛出关键字无法处理字段声明中引发的异常



在下面的代码中,在匿名类实例化中编写的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

最新更新