Java Reference
In-Depth Information
Please enter an integer numerator: 100
Please enter an integer denominator: 7
Result: 100 / 7 = 14
Please enter an integer numerator: 100
Please enter an integer denominator: 0
Exception: java.lang.ArithmeticException: / by zero
Zero is an invalid denominator. Please try again.
Please enter an integer numerator: 100
Please enter an integer denominator: 7
Result: 100 / 7 = 14
Please enter an integer numerator: 100
Please enter an integer denominator: hello
Exception: java.util.InputMismatchException
You must enter integers. Please try again.
Please enter an integer numerator: 100
Please enter an integer denominator: 7
Result: 100 / 7 = 14
Fig. 11.3 | Handling ArithmeticException s and InputMismatchException s. (Part 2 of 2.)
The first sample execution in Fig. 11.3 does not encounter any problems. In the
second execution the user enters a zero denominator , and an ArithmeticException excep-
tion occurs. In the third execution the user enters the string "hello" as the denominator,
and an InputMismatchException occurs. For each exception, the user is informed of the
mistake and asked to try again, then is prompted for two new integers. In each sample exe-
cution, the program runs to completion successfully.
Class InputMismatchException is imported in line 3. Class ArithmeticException
does not need to be imported because it's in package java.lang . Line 18 creates the
boolean variable continueLoop , which is true if the user has not yet entered valid input.
Lines 20-48 repeatedly ask users for input until a valid input is received.
Enclosing Code in a try Block
Lines 22-33 contain a try block , which encloses the code that might throw an exception
and the code that should not execute if an exception occurs (i.e., if an exception occurs,
the remaining code in the try block will be skipped). A try block consists of the keyword
try followed by a block of code enclosed in curly braces. [ Note: The term “ try block”
sometimes refers only to the block of code that follows the try keyword (not including the
try keyword itself). For simplicity, we use the term “ try block” to refer to the block of
 
Search WWH ::




Custom Search