Java Reference
In-Depth Information
Display 9.4
Using a Programmer-Defined Exception Class
(part 3 of 3)
Sample Dialogue 3
Enter numerator:
11
Enter denominator:
0
Division by Zero!
Try again.
Enter numerator:
11
Enter denominator:
Be sure the denominator is not zero.
0
I cannot do division by zero.
Aborting program.
This exception is caught in the
catch
block shown in Display 9.4. Consider the fol-
lowing 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:
Division by Zero!
The definition of the class
DivisionByZeroException
in Display 9.3 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.4 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.4, the
try
block is the normal part of the program. If all
goes normally, 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