Java Reference
In-Depth Information
throw
statement
This
try
block contains the following three
throw
statements:
throw new
Exception("Lesson is canceled. No students.");
throw new
Exception("Lesson is canceled. No men.");
throw new
Exception("Lesson is canceled. No women.");
The value thrown is an argument to the
throw
operator and is always an object of some
exception class. The execution of a
throw
statement is called
throwing an exception
.
throwing an
exception
throw
Statement
SYNTAX
throw new
Exception_Class_Name (Possibly_Some_Arguments);
When the
throw
statement is executed, the execution of the surrounding
try
block is stopped
and (normally) control is transferred to a
catch
block. The code in the
catch
block is executed
next. See the box entitled
"try-throw-catch"
later in this chapter for more details.
EXAMPLE
throw new
Exception("Division by zero.");
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.");
And suppose the following is a
catch
block immediately following the
try
block:
catch
(Exception e)
{
System.out.println(e.getMessage());
System.out.println("Program aborted.");
System.exit(0);
}
In this case, the method call
e.getMessage()
returns the string
"Input must be positive."