Java Reference
In-Depth Information
EXAMPLE:
(continued)
The
throw
operator causes a change in the flow of control and it delivers the
Exception
object to
a suitable place, as we are about to explain. When the
throw
operator is executed, the
try
block ends
immediately and control passes to the following
catch
block. (If it helps, you can draw an analogy
between the execution of the
throw
operator in a
try
block and the execution of a
break
statement
in a loop or
switch
statement.) When control is transferred to the
catch
block, the
Exception
object that is thrown is plugged in for the
catch
block parameter
e
. So, the expression
e.getMessage()
returns the string
"Lesson is canceled. No men."
The method
getMessage()
of the class
Exception
is an accessor method that retrieves the
String
in the private instance variable
of the
Exception
object—that is, the
String
used as an argument to the
Exception
constructor.
To see if you get the basic idea of how this exception throwing mechanism works, study the
sample dialogues. The next few sections explain this mechanism in more detail.
try-throw-catch
Mechanism
The basic way of handling exceptions in Java consists of the
try-throw-catch
trio.
The general setup consists of a
try
block followed by one or more
catch
blocks. First
let's describe what a try block is. A
try
block
has the syntax
try
{
Some_Code
}
try
block
This
try
block contains the code for the basic algorithm that tells what to do when
everything goes smoothly. It is called a
try
block because it “tries” to execute the case
where all goes smoothly.
Now, if something exceptional does happen, you want to throw an exception,
which is a way of indicating that something unusual happened. So the basic outline,
when we add a
throw
, is as follows:
try
{
Code_That_May_Throw_An_Exception
}
The following is an example of a
try
block with
throw
statements included (copied
from Display 9.2):
try
{
if
(men == 0 && women == 0)
throw new
Exception("Lesson is canceled. No students.");
else
if
(men == 0)
throw new
Exception("Lesson is canceled. No men.");
else
if
(women == 0)
throw new
Exception("Lesson is canceled. No women.");