Java Reference
In-Depth Information
InputMismatchException is in the standard Java package java.util , so if your
program mentions InputMismatchException , then it needs an import statement,
such as the following:
import java.util.InputMismatchException;
Display 9.1 contains an example of how you might usefully catch an
InputMismatchException . This program gets an input int value from the keyboard
and then does nothing with it other than echo the input value. However, you can use
code such as this to require robust input for any program that uses keyboard input.
The Tip “Exception Control Loops” explains the general technique we used for the
loop in Display 9.1 .
TIP: Exception Controlled Loops
Sometimes when an exception is thrown, such as an InputMismatchException for
an ill-formed input, you want your code to simply repeat some code so that the user
can get things right on a second or subsequent try. One way to set up your code to
repeat a loop every time a particular exception is thrown is as follows:
boolean done = false ;
while (!done)
{
try
{
Code that may throw an exception in the class Exception_Class.
done = true ;// Will end the loop.
<Possibly more code.>
}
catch ( Exception_Class e)
{
<Some code.>
}
}
Note that if an exception is thrown in the fi rst piece of code in the try block, then
the try block ends before the line that sets done to true is executed, so the loop body
is repeated. If no exception is thrown, then done is set to true and the loop body is
not repeated.
Display 9.1 contains an example of such a loop. Minor variations on this outline
can accommodate a range of different situations for which you want to repeat code on
throwing an exception.
 
Search WWH ::




Custom Search