Java Reference
In-Depth Information
This exception is caught in the catch block shown in Display 9.5 . Consider the
following line from that catch block:
System.out.println(e.getMessage());
This line produces the following output to the screen in Sample Dialogues 2 and 3
(in Display 9.5 ):
Division by Zero!
The definition of the class DivisionByZeroException in Display 9.4 has a second
constructor with one parameter of type String . This constructor allows you to choose any
message you like when you throw an exception. If the throw statement in Display 9.5 had
instead used the string argument
throw new DivisionByZeroException(
"Oops. Shouldn't divide by zero.");
then in Sample Dialogues 2 and 3, the statement
System.out.println(e.getMessage());
would have produced the following output to the screen:
Oops. Shouldn't divide by zero.
Notice that in Display 9.5 , the try block is the normal part of the program. If all goes
routinely, that is the only code that will be executed, and the dialogue will be like the one
shown in Sample Dialogue 1. In the exceptional case, when the user enters a zero for a
denominator, the exception is thrown and then is caught in the 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 exception
classes you defi ne.
 
Search WWH ::




Custom Search