从下面的文章中,它说“至少,每当你捕获InterruptedException并且不重新抛出它时,在返回之前重新中断当前线程。”。
我的问题是为什么不重新抛出InterruptedException或者不能从Runnable重新抛出它? http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html
答案 0 :(得分:2)
因为你做不到。 InterruptedException
是一个未经声明的异常,未被Runnable.run()
抛出。而且出于同样的原因,你不能只修改方法签名。
答案 1 :(得分:0)
如果(1)你有一个外部InterruptedException
块来处理它,或者(2)允许当前方法抛出给定的,你可以重新抛出一个catch
,这是一个已检查的异常异常类型,例如void read() throws IOException
。
不允许覆盖Runnable.run()
的方法抛出异常,因此您只能在第一种情况下重新抛出InterruptedException
:
@Override
public void run() {
try {
// some logic
try {
// some logic that throws InterruptedException
} catch (InterruptedException e) {
// here you can either rethrow "e"
// to be dealt in the outer catch block or
// reinterrupt the current thread
throw e;
}
} catch (InterruptedException e) {
// here you cannot rethrow "e"
// so you have to deal with it or
// reinterrupt the current thread
}
}