Java Reference
In-Depth Information
Self-Test Exercises
1. How would the dialogue in Display 9.1 change if you were to omit the following
line from the catch block? (Try it and see.)
keyboard.nextLine();
2. Give the defi nition for the following method. Use the techniques given in
Display 9.1 .
/**
Precondition: keyboard is an object of the class Scanner that
has been set up for keyboard input (as we have been doing
right along). Returns: An int value entered at the keyboard.
If the user enters an incorrectly formed input, she or he
is prompted to reenter the value,
*/
public static int getInt(Scanner keyboard)
Throwing Exceptions
In the previous example, an exception was thrown by the nextInt() method if a
noninteger was entered. We did not write the method that threw the exception; we
were responsible only for catching and handling any exceptions. For many programs,
this pattern is all that is necessary.
However, it is also possible for your own code to throw the exception. To do this,
use a throw statement inside the try block in the format
throw new Exception( String_describing _the_exception );
The following is an example of a try block with throw statements included (copied
from Display 9.3, which computes pairs of men and women for a dance studio):
try
{
if (men == 0 && women == 0)
throw new Exception("Lesson is canceled. No students.");
else if (men == 0)
throw new Exception("Lesson is canceled. No men.");
else if (women == 0)
throw new Exception("Lesson is canceled. No women.");
// women >= 0 && men >= 0
if (women >= men)
System.out.println("Each man must dance with " +
women/( double )men + "women.");
else
System.out.println("Each woman must dance with " +
men/( double )women + " men.");
}
 
Search WWH ::




Custom Search