Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^436) | Exceptions and Additional Control Structures
void caller()
{
// Some statements
try
{
// Statements
someMethod();
// Statements
}
catch (SomeException except)
{
// Statements to handle exception
}
// More statements
}
void someMethod() throws SomeException
{
// Some statements
if (error)
throw new SomeException("Message.");
// More statements
}
Call
Normal
Return
Return from
Thrown Exception
Figure 9.1 Throwing an Exception to be Caught in a Calling Method
back to main. If mainfails to catch the exception, then the JVM handles it by stopping the ap-
plication and displaying an error message.
As we’ve seen previously, we must handle each class of exception either by catching it
or explicitly forwarding it with a throwsclause in the method heading. Thus an exception can
cause a chain of returns that reaches the JVM only when our code is written to allow it to do
so. We can’t generate an exception that is accidentally uncaught.
We can throw any of the standard exceptions that Java provides. For example:
throw newFileNotFoundException(filename);
It’s actually quite rare to throw one of the predefined exceptions. One situation where
we might do so is when we’ve caught such an exception in a catchclause but some aspect
of handling it must be passed to a higher-level method.
Instead of throwing a predefined exception, we typically want to define and throw a
new exception class. A user of the class must then handle that class of exception. For example,
in our Addressclass from Chapter 7, we could have validated the ZIP code. Basic ZIP codes are
five digits or less. If a ZIP code is greater than 99,999, we can throw a ZipCodeInvalidException
in the constructor for an Addressobject as follows:
publicAddress(String name, String city, String state, int zipCode)
throwsZipCodeInvalidException
{
if (zipCode <= 99999 )
this.zipCode = zipCode; // If valid, store value
else // throw exception
throw newZipCodeInvalidException("" + zipCode);

Free download pdf