Java Reference
In-Depth Information
Sample Runs:
Sample Run 1: (In this sample run, the user input is shaded.)
Line 11: Enter an integer: 56
Line 5: number = 56
Sample Run 2: (In this sample run, the user input is shaded.)
Line 11: Enter an integer: 56t7
Line 7: Exception java.util.InputMismatchException
The preceding program contains the method getNumber , which reads an integer and
returns it to the method main . If the number entered by the user contains a nondigit
character, the method getNumber throws an InputMismatchException . The catch
block in Line 15 catches this exception. Rather than handle this exception, the method
getNumber rethrows this exception (see the statement in Line 16).
The catch blockinLine6ofthemethod main also catches the InputMismatchException .
In Sample Run 1, the method getNumber successfully reads the number and returns it to
the method main . In Sample Run 2, the user enters an invalid number. The statement in
Line 12 throws an InputMismatchException , which is caught and rethrown by the
catch block starting at Line 15. After the statement in Line 16 executes, control goes back
to the method main (Line 4), which throws an InputMismatchException thrown by
the method getNumber . The catch block in Line 6 catches this exception, and the
statement in Line 7 outputs the appropriate message.
Example 11-7 illustrates how to rethrow the same exception caught by a catch block.
When an exception occurs, the system creates an object of a specific exception class .In
fact, you can also create your own exception objects and throw them using the throw
statement. In this case, the general syntax used for the throw statement is:
1
1
throw new ExceptionClassName(messageString);
Of course, you could have first created the object and then used the reference to the
object in the throw statement.
Example 11-8 illustrates how to create and throw an exception object.
EXAMPLE 11-8
//RethrowExceptionExmp2
import java.util.*;
public class RethrowExceptionExmp2
{
static Scanner console = new Scanner(System.in);
 
Search WWH ::




Custom Search