Java Reference
In-Depth Information
catch
block. The
catch
block outputs the message of the exception and then calls the
method
secondChance
. The method
secondChance
gives the user a second chance to
enter the input correctly and then carries out the calculation. If the user tries a second
time to divide by zero, the method ends the program. The method
secondChance
is
there only for this exceptional case. So, we have separated the code for the exceptional
case of a division by zero into a separate method, where it will not clutter the code for
the normal case.
TIP: Preserve
getMessage
For all predefined exception classes,
getMessage
will return the string that is passed as
an argument to the constructor (or will return a default string if no argument is used
with the constructor). For example, if the exception is thrown as follows:
throw new
Exception("Wow, this is exceptional!");
then
"Wow, this is exceptional!"
is used as the value of the
String
instance variable
of the object created. If the object is called
e
, the method invocation
e.getMessage()
returns
"Wow, this is exceptional!"
You want to preserve this behavior in the excep-
tion classes you define.
For example, suppose you are defining 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 defined 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 con-
structor 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 defined. A
full definition of the class
NegativeNumberException
is given in Display 9.8.
■