Java Reference
In-Depth Information
Sample Run: (In this sample run, the user input is shaded.)
Line 7: Enter an integer: 34t5
Line 14: Exception java.util.InputMismatchException 34t5
Line 7: Enter an integer: 398se2
Line 14: Exception java.util.InputMismatchException 398se2
Line 7: Enter an integer: r45
Line 14: Exception java.util.InputMismatchException r45
Line 7: Enter an integer: 56
Line 11: number = 56
In the preceding program, the statement in Line 7 prompts the user to enter an integer.
The statement in Line 8 inputs the integer entered by the user into the variable number .
If the user enters a valid integer, then that integer is stored in number . Then, the
statement in Line 10 sets the boolean variable done to true . After the statement in
Line 11 executes, the next statement executed is the expression !done in Line 15. If done
is true , then !done is false , so the while loop terminates.
Suppose that the user does not enter a valid integer. Because the next input (token)
cannot be expressed as an integer, the statement in Line 8 throws an
InputMismatchException and control is transferred to the catch block starting at
Line 12. Notice that the invalid number entered by the user is still the next input (token)
in the input stream. Therefore, the statement in Line 13 reads that invalid number and
assigns that input (token) to str . The statement in Line 14 outputs the exception as well
as the invalid input. Notice that we can output the invalid input because the program
captured the invalid input at Line 13. The do ... while loop continues to prompt the user
until the user inputs a valid integer.
Notice that in the sample run, the first, second, and third inputs are 34t5 , 398se2 , and
r45 , which contain nondigit characters. The fourth input, which is 56 , is a valid integer.
1
1
Log the Error and Continue
A program that terminates when an exception occurs usually assumes that the
termination is reasonably safe. On the other hand, if your program is designed to
run a nuclear reactor or continuously monitor a satellite, it cannot be terminated if
an exception occurs. These programs should report the exception, but the program
must continue to run.
For example, consider a program that analyzes airline-ticketing transactions. Because
a large number of ticketing transactions take place each day, a program is run daily to
validate that day's transactions. This type of program would take an enormous
amount of time to process the transactions. Therefore, when an exception occurs,
the program should write the exception into a file and continue to analyze the
transactions.
 
Search WWH ::




Custom Search