Java Reference
In-Depth Information
One thing is true at all times: It's better to pass on exceptions to calling methods than to
catch them and do nothing in response.
In addition to declaring methods that throw exceptions, there's one other instance in
which your method definition may include a throws clause: Within that method, you
want to call a method that throws an exception, but you don't want to catch or deal with
that exception.
Rather than using the try and catch clauses in your method's body, you can declare
your method with a throws clause so that it, too, might possibly throw the appropriate
exception. It's then the responsibility of the method that calls your method to deal with
that exception. This is the other case that tells the Java compiler that you have done
something with a given exception.
Using this technique, you could create a method that deals with number format excep-
tions without a try - catch block:
public void readFloat(String input) throws NumberFormatException {
float in = Float.parseFloat(input);
}
After you declare your method to throw an exception, you can use other methods that
also throw those exceptions inside the body of this method, without needing to protect
the code or catch the exception.
You can, of course, deal with other exceptions using try and catch
in the body of your method in addition to passing on the excep-
tions you listed in the throws clause. You also can both deal with
the exception in some way and then rethrow it so that your
method's calling method has to deal with it anyhow. You learn how
to throw methods in the next section.
NOTE
throws and Inheritance
If your method definition overrides a method in a superclass that includes a throws
clause, there are special rules for how your overridden method deals with throws . Unlike
other parts of the method signature that must mimic those of the method it is overriding,
your new method does not require the same set of exceptions listed in the throws clause.
Because there's a possibility that your new method might deal better with exceptions
instead of just throwing them, your method can potentially throw fewer types of
Search WWH ::




Custom Search