Java Reference
In-Depth Information
and in the
catch
block, give code for some alternative action, such as asking the user to
reenter the input.
InputMismatchException
is a descendent class of
RuntimeException
,
so you are not required to account for an
InputMismatchException
by catching it in a
catch
block or declaring it in a
throws
clause. However, you are allowed to catch an
InputMismatchException
in a
catch
block, which can sometimes be useful.
InputMismatchException
is in the standard Java package
java.util
and so if your
program mentions
InputMismatchException
, then it needs an import statement, such
as the following:
import
java.util.InputMismatchException;
Display 9.11 contains a sample of how you might usefully catch an
Input-
MismatchException
. 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
like this to give robust input to any program that uses keyboard input. The following
Tip explains the general technique we used for the loop in Display 9.11.
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 (or
whatever) 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 first piece of code in the
try
block, then the
try
block ends before the line that sets
done
to
true
is executed and 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.11 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.
■