Programming and Problem Solving with Java

(やまだぃちぅ) #1
9.1 Exception-Handling Mechanism | 437

}

We would call this constructor within a try-catchstatement:

try
{
myAddress = new Address("myName", "Austin", "Texas", 78744);
}
catch(ZipCodeInvalidException zip)
{
// Exception handler
// Print bad ZIP code
System.out.println(zip.getMessage() + " is invalid");
}


Whatever method is attempting to create an Addressobject with an invalid ZIP code is
then responsible for handling the error. Of course, we also need to define the class called
ZipCodeInvalidException.


Exception Classes


A throwstatement must have an exception object to throw. Exception objects are very sim-
ple to create. Their class name conveys the basic information that tells the JVM what sort of
exception is being thrown. Typically, all we need to add is an error message or some other
piece of information that helps the catchclause handle the error.
The predefined type Exceptionis derived from Throwableand provides a field for an er-
ror message. All we have to do is extend it with our own class name and supply a pair of con-
structors that call super. Here is how we define zipCodeInvalidException:


packageaddressBook;
public classZipCodeInvalidException extendsException
{
publicZipCodeInvalidException()
{
super();
}
publicZipCodeInvalidException(String message)
{
super(message);
}
}

Free download pdf