Java Reference
In-Depth Information
TIP: (continued)
For example, suppose you are defi ning an exception class named
NegativeNumber
Exception
. Be sure to include a constructor with a string parameter that begins with
a call to
super
, as illustrated by the following constructor:
public
NegativeNumberException(String message)
{
super
(message);
}
The call to
super
is a call to a constructor of the base class. If the base class constructor
handles the message correctly, then so will a class defi ned in this way.
You should also include a no-argument constructor in each exception class. This
no-argument constructor should set a default value to be retrieved by
getMessage
. The
constructor should begin with a call to
super
, as illustrated by the following constructor:
public
NegativeNumberException()
{
super
("Negative Number Exception!");
}
If
getMessage
works as we described for the base class, then this sort of no-argument
constructor will work correctly for the new exception class being defi ned. A full defi ni-
tion of the class
NegativeNumberException
is given in Display 9.9 .
■
Exception Object Characteristics
The two most important things about an exception object are its type (the exception class) and
a message that it carries in an instance variable of type
String
. This string can be recovered
with the accessor method
getMessage
. This string allows your code to send a message
along with an exception object, so that the
catch
block can use the message.
Programmer-Defined Exception Classes
You may define your own exception classes, but every such class must be a derived class
of an already existing exception class (either from one of the standard Java libraries or
programmer defined).
GUIDELINES
•
If you have no compelling reason to use any other class as the base class, use the
class
Exception
as the base class.
•
You should define two (or more) constructors, as described later in this list.
(continued)