【问题标题】:Why throws keyword cannot handle the exception thrown in field declaration [duplicate]为什么 throws 关键字无法处理字段声明中抛出的异常 [重复]
【发布时间】:2018-07-07 11:34:30
【问题描述】:

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

【问题讨论】:

  • 这与字段声明无关。尝试将 Runnable task = ... 放入方法中:您将得到完全相同的错误。

标签: java exception-handling try-catch throws


【解决方案1】:

run() 方法缺少throws InterruptedException 子句。 main() 有一个,run() 定义在 main() 内部定义的类中并不重要。它们是两种不同的方法。

不过,不可能向run() 添加一个,因为Runnable 不允许run()throws 子句。因此,唯一的解决方案是用 try/catch 块包装sleep

【讨论】:

  • 同样的答案。嵌套无关紧要。
  • 所以,这意味着在匿名内部类中,只能使用 try-catch 块来处理异常。
  • @SKumar no:必须始终处理 checked 异常,无论是使用 try/catch 还是在方法上使用 throws 声明。您不能将 throws 声明添加到与它所覆盖的任何 throws 声明不协变的方法中。 Runnable.run() 隐含 throws RuntimeException, Error; InterruptedException 与两者都不协变,因此您不能添加 throws InterruptedException。因此,您必须使用 try/catch。如果您的匿名课程是例如Callable,你可以使用throws,因为Callable.call() 会抛出Exception
猜你喜欢
  • 1970-01-01
  • 2012-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多