Java 为什么throws关键字无法处理字段声明中引发的异常
在下面的代码中,Java 为什么throws关键字无法处理字段声明中引发的异常,java,exception-handling,try-catch,throws,Java,Exception Handling,Try Catch,Throws,在下面的代码中,Thread.sleep(3000)只能使用try-catch块进行处理。为什么抛出InterruptedException子句不允许异常传播 public static void main(String[] args) throws InterruptedException { Runnable task = new Runnable() { public void run() { // below line explicitly
Thread.sleep(3000)在匿名类实例化中编写的代码>只能使用try-catch块进行处理。为什么抛出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()
方法缺少抛出InterruptedException
子句。无论main()
是否有一个,也不管run()
是在main()
内部定义的类中定义的。这是两种不同的方法
但是,将一个添加到run()
是不可能的,因为Runnable
不允许run()
具有抛出
子句。因此,唯一的解决方案是用try/catch块包装sleep
。这与字段声明无关。尝试将可运行任务=…
放在一个方法中:您将得到完全相同的错误。相同的答案。嵌套并不重要。因此,这意味着在匿名内部类中,只能使用try-catch块来处理异常。@SKumar否:必须始终使用try/catch或方法上的throws
声明来处理选中的异常。不能将throws
声明添加到与其覆盖的throws
声明不一致的方法中Runnable.run()
隐式地抛出RuntimeException,错误
InterruptedException
与两者都是协变的,因此不能添加抛出InterruptedException
。因此,您必须使用try/catch。如果您的匿名类是例如可调用的
,您可以使用抛出
,因为可调用的.call()
抛出异常
。