Java Reference
In-Depth Information
NOTE
The finally statement is useful outside exceptions—it can exe-
cute cleanup code after a return , break , or continue statement
inside loops. For the latter cases, you use a try statement with a
finally but without a catch statement.
Declaring Methods That Might Throw
Exceptions
In previous examples, you learned how to deal with methods that might throw exceptions
by protecting code and catching any exceptions that occur. The Java compiler checks to
make sure that you've dealt with a method's exceptions—but how did it know which
exceptions to tell you about in the first place?
The answer is that the original method indicated the exceptions that it might possibly
throw as part of its definition. You can use this mechanism in your own methods—in
fact, it's good style to do so to make sure that users of your classes are alerted to the
errors your methods might experience.
To indicate that a method will possibly throw an exception, you use a special clause in
the method definition called throws .
The throws Clause
If some code in your method's body might throw an exception, add the throws keyword
after the closing parenthesis of the method followed by the name or names of the excep-
tion that your method throws, as in this example:
public boolean getFormula(int x, int y) throws NumberFormatException {
// body of method
}
If your method might throw multiple kinds of exceptions, you can declare them all in the
throws clause separated by commas:
public boolean storeFormula(int x, int y)
throws NumberFormatException, EOFException {
// body of method
7
}
 
Search WWH ::




Custom Search