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
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...)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With