Page 598 - Introduction to Programming with Java: A Problem Solving Approach
P. 598
564 Chapter 14 Exception Handling
public static int getIntFromUser()
{
Scanner stdIn = new Scanner(System.in);
String xStr;
// user entry
boolean valid; // is user entry a valid integer?
int x;
// integer form of user entry
System.out.print("Enter an integer: ");
xStr = stdIn.next();
do
{
try
{
}
valid = false;
x = Integer.parseInt(xStr);
valid = true;
catch (NumberFormatException nfe)
{
System.out.print("Invalid entry. Enter an integer: ");
xStr = stdIn.next(
}
}
while (!valid);
Apago PDF Enhancer
compile-time error: x might not have been initialized
}
// end getIntFromUser
return x;
);
compile-time error: valid might not have been initialized
Figure 14.5 A method that illustrates the problem with initializing inside a try block
conversion fails? The valid variable never gets set to true because an exception is thrown and the JVM immediately jumps out of the try block. So this code seems reasonable. Unfortunately, “seems reasonable” isn’t good enough this time.
Can you figure out the compile-time errors? If not, don’t feel bad; we didn’t see them until after the compiler helped us. As shown by the callouts in Figure 14.5, the compiler complains that the valid and x variables might not have been initialized. Why all the fuss? Can’t the compiler see that valid and x are as- signed values in the try block? Yes, the compiler can see the assignments, but remember that the compiler is a pessimist. It assumes that all statements inside a try block are skipped. Even though we know that the valid = false;statementisinnoactualdangerofbeingskipped(it’sasimpleassignment,andit’sthe first line in the try block), the compiler still assumes that it gets skipped.
What’sthesolution?(1)Movethevalid = false;assignmentuptovalid’sdeclarationline. (2) Initialize x to 0 as part of x’s declaration line. Figure 14.6 contains the corrected implementation.
14.6 Two Categories of Exceptions—Checked and Unchecked
Exceptions fall into two categories—checked and unchecked. Checked exceptions must be checked with a try-catch mechanism. Unchecked exceptions can optionally be checked with a try-catch mechanism, but it’s not a requirement.