Java Reference
In-Depth Information
EXAMPLE
In the following,
e
is the
catch
block parameter.
catch
(Exception e)
{
System.out.println(e.getMessage());
System.out.println("Aborting program.");
System.exit(0);
}
Let's consider two possible cases of what can happen when a
try
block is executed:
(1) no exception is thrown in the
try
block, and (2) an exception is thrown in the
try
block and caught in the
catch
block. (Later in the Tip, “What Happens if an
Exception Is Never Caught?,” we will describe a third case where the
catch
block does
not catch the exception.)
• If no exception is thrown, the code in the
try
block is executed to the end of the
try
block, the
catch
block is skipped, and execution continues with the code placed
after the
catch
block.
• If an exception is thrown in the
try
block, the rest of the code in the
try
block
is skipped and (in simple cases) control is transferred to a following
catch
block.
The thrown object is plugged in for the
catch
block parameter, and the code in
the
catch
block is executed. And then (provided the
catch
block code does not
end the program or do something else to end the
catch
block code prematurely), the
code that follows that
catch
block is executed.
Exception Handling with the
Scanner
Class
As a concrete example, consider a program that reads an
int
value from the keyboard
using the
nextInt
method of the
Scanner
class. You have probably noticed that
the program will end with an error message if the user enters something other than
a well-formed
int
value. That is true as far as it goes, but the full detail is that
if the user enters something other than a well-formed
int
value, an exception of
type
InputMismatchException
will be thrown. If the exception is not caught, your
program ends with an error message. However, you can catch the exception, and
in the
catch
block, give code for some alternative action, such as asking the user to
reenter the input. You are not required to account for an
InputMismatchException
by catching it in a
catch
block or declaring it in a
throws
clause (this is because
InputMismatchException
is a descendent class of
RuntimeException
). However,
you are allowed to catch an
InputMismatchException
in a
catch
block, which can
sometimes be useful.