Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 816
fireshadow52 Avatar asked May 28 '10 17:05

fireshadow52


2 Answers

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

like image 85
Jon Skeet Avatar answered Sep 20 '22 04:09

Jon Skeet


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.

like image 41
Jesper Avatar answered Sep 23 '22 04:09

Jesper