Question

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

Was it helpful?

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...)

OTHER TIPS

There are two kinds of exceptions in Java: checked and unchecked exceptions.

For checked exceptions, the compiler checks if your program handles them, either by catching them or by specifying (with a throws clause) that the method in which the exception might happen, that the method might throw that kind of exception.

Exception classes that are subclasses of java.lang.RuntimeException (and RuntimeException itself) are unchecked exceptions. For those exceptions, the compiler doesn't do the check - so you are not required to catch them or to specify that you might throw them.

Class InterruptedException is a checked exception, so you must either catch it or declare that your method might throw it. You are throwing the exception from the catch block, so you must specify that your method might throw it:

public void invalid() throws InterruptedException {
    // ...

Exception classes that extend java.lang.Exception (except RuntimeException and subclasses) are checked exceptions.

See Sun's Java Tutorial about exceptions for detailed information.

InterruptedException is not a RuntimeException so it must be caught or checked (with a throws clause on the method signature). You can only throw a RuntimeException and not be forced by the compiler to catch it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top