This question already has an answer here:
这个问题在这里已有答案:
- java - checked exception for 'throws' in overridden method 2 answers
java - 在重写的方法2答案中检查'throws'的异常
In the code below, Thread.sleep(3000);
written inside the anonymous class instantiation can be handled only using a try-catch block. Why doesn't the throws InterruptedException
clause allow the exception to propagate?
在下面的代码中,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);
}
};
}
1 个解决方案
#1
2
The run()
method lacks a throws InterruptedException
clause. It doesn't matter that main()
has one, nor that run()
is defined in an class defined inside of main()
. They're two different methods.
run()方法缺少抛出InterruptedException子句。 main()有一个没关系,run()是在main()内定义的类中定义的。他们是两种不同的方法。
Adding one to run()
isn't possible, though, because Runnable
doesn't allow run()
to have a throws
clause. Therefore, the only solution is to wrap the sleep
with a try/catch block.
但是,添加一个到run()是不可能的,因为Runnable不允许run()具有throws子句。因此,唯一的解决方案是使用try / catch块包装睡眠。
#1
2
The run()
method lacks a throws InterruptedException
clause. It doesn't matter that main()
has one, nor that run()
is defined in an class defined inside of main()
. They're two different methods.
run()方法缺少抛出InterruptedException子句。 main()有一个没关系,run()是在main()内定义的类中定义的。他们是两种不同的方法。
Adding one to run()
isn't possible, though, because Runnable
doesn't allow run()
to have a throws
clause. Therefore, the only solution is to wrap the sleep
with a try/catch block.
但是,添加一个到run()是不可能的,因为Runnable不允许run()具有throws子句。因此,唯一的解决方案是使用try / catch块包装睡眠。