Java Reference
In-Depth Information
public static void main(String[] args)
//Line 1
{
int number;
//Line 2
try
//Line 3
{
number = getNumber();
//Line 4
System.out.println("Line 5: number = "
+ number);
//Line 5
}
catch (InputMismatchException imeRef)
//Line 6
{
System.out.println("Line 7: Exception "
+ imeRef.toString());
//Line 7
}
}
public static int getNumber()
throws InputMismatchException
//Line 8
{
int num;
//Line 9
try
//Line 10
{
System.out.print("Line 11: Enter an "
+ "integer: ");
//Line 11
num = console.nextInt();
//Line 12
System.out.println();
//Line 13
return num;
//Line 14
}
catch (InputMismatchException imeRef)
//Line 15
{
System.out.println("Line 16: Exception "
+ imeRef.toString());
//Line 16
throw new InputMismatchException
("getNumber");
//Line 17
}
}
}
Sample Run: (In this sample run, the user input is shaded.)
Line 11: Enter an integer: 563r9
Line 16: Exception java.util.InputMismatchException
Line 7: Exception java.util.InputMismatchException: getNumber
The preceding program works similarly to the program in Example 11-7. The difference
is in the catch block starting at Line 15, in the method getNumber . The catch block in
Line 15 catches an InputMismatchException , outputs an appropriate message in Line
16, and then in Line 17 creates an InputMismatchException object with the message
string "getNumber" and throws the object. The catch block starting at Line 6 in the
 
Search WWH ::




Custom Search