在下面的文章中,它说:“至少,每当您捕获InterruptedException并且不重新抛出它时,请在返回之前重新中断当前线程。”。
我的问题是为什么不重新抛出InterruptedException或不能将其从Runnable抛出?
http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html
最佳答案
如果(1)您有一个外部InterruptedException
块要处理它,或者(2)当前方法被允许抛出给定的异常类型,例如catch
。
覆盖void read() throws IOException
的方法不允许引发异常,因此,在第一种情况下,您只能重新抛出Runnable.run()
:
@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
}
}