Search code examples
javaexceptionthrow

throw exception


Why can't you throw an InterruptedException in the following way:

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;
}

I went to http://java24hours.com, but it didn't tell me why I couldn't throw an InterruptedException.
If anyone knows why, PLEASE tell me! I'm desperate! :S


Solution

  • You can only throw it if the method you're writing declares that it throws InterruptedException (or a base class).

    For example:

    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;
      }
    }
    

    You should read up on checked exceptions for more details.

    (Having said this, calling wait() on System.in almost certainly isn't doing what you expect it to...)