Java Reference
In-Depth Information
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 recov-
ered 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 program-
mer 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.
Your exception class inherits the method getMessage . Normally, you do not need to
add any other methods, but it is legal to do so.
You should start each constructor definition with a call to the constructor of the base
class, such as the following:
super ("Sample Exception thrown!");
You should include a no-argument constructor, in which case the call to super should
have a string argument that indicates what kind of exception it is. This string can then
be recovered by using the getMessage method.
You should also include a constructor that takes a single string argument. In this
case, the string should be an argument in a call to super . That way, the string can be
recovered with a call to getMessage .
EXAMPLE
public class SampleException extends Exception
{
public SampleException()
{
super ("Sample Exception thrown!");
}
public SampleException(String message)
{
super (message);
}
}
extra code
on CD
The class SampleException is on the CD that comes with this text.
Search WWH ::




Custom Search