抛出异常

fir*_*w52 8 java exception throw

为什么不能以下列方式抛出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;
}
Run Code Online (Sandbox Code Playgroud)

我去了http://java24hours.com,但它没有告诉我为什么我不能抛出InterruptedException.
如果有人知道为什么,告诉我!我很绝望!:S

Jon*_*eet 14

如果您正在编写的方法声明它抛出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;
  }
}
Run Code Online (Sandbox Code Playgroud)

您应该阅读已检查的异常以获取更多详细信息.

(说到此,呼吁wait()System.in几乎可以肯定不会做你希望它是什么......)