为什么你不能通过以下方式抛出 InterruptedException:
try {
System.in.wait(5) //Just an example
} catch (InterruptedException exception) {
exception.printStackTrace();
//On this next line I am confused as to why it will not let me throw the exception
throw exception;
}
我去了http://java24hours.com ,但它没有告诉我为什么我不能抛出 InterruptedException。
如果有人知道原因,请告诉我!我很绝望! :S
最佳答案
只有当您编写的方法声明它抛出InterruptedException
(或基类)时,您才能抛出它。
例如:
public void valid() throws InterruptedException {
try {
System.in.wait(5) //Just an example
} catch (InterruptedException exception) {
exception.printStackTrace();
throw exception;
}
}
// Note the lack of a "throws" clause.
public void invalid() {
try {
System.in.wait(5) //Just an example
} catch (InterruptedException exception) {
exception.printStackTrace();
throw exception;
}
}
您应该阅读已检查的异常以了解更多详细信息。
(话虽如此,在 System.in
上调用 wait()
几乎肯定不会按照您的预期进行...)
关于java - 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2931176/