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 we will describe a third case where the
catch
block does not catch the exception.)
1. 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.
2. 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.
The
getMessage
Method
Every exception has a
String
instance variable that contains some message, which typically
identifies the reason for the exception. For example, if the exception is thrown as follows:
throw new
Exception(
String_Argument
);
then the string given as an argument to the constructor
Exception
is used as the value of this
String
instance variable. If the object is called
e
, then the method call
e.getMessage()
returns this string.
EXAMPLE
Suppose the following
throw
statement is executed in a
try
block:
throw new
Exception("Input must be positive.");
(continued)