Java Reference
In-Depth Information
EXAMPLE:
(continued)
unary
+
or unary − operators. To make it look more like an operator, you can write it
with parentheses around the argument, as follows:
throw
(
new
Exception("Lesson is canceled. No men."));
Although it is perfectly legal and sensible to include these extra parentheses, nobody
includes them.
To understand this process of throwing, you need to know two things: What is
this
Exception
class? And what does the
throw
operator do with the
Exception
object? The class
Exception
is another class from the standard Java package
java.
lang
. As you have already seen, the class
Exception
has a constructor that takes a
single
String
argument. The
Exception
object created stores this
String
argument
(in a private instance variable). As you will see, this
String
argument can later be
retrieved from the
Exception
object.
The
throw
operator causes a change in the flow of control and 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 in Displays 9.2 and 9.3 . The next few sections explain
this mechanism in more detail.
Display 9.2
Handling a Special Case without Exception Handling
(part 1 of 3)
1
import
java.util.Scanner;
2
public class
DanceLesson
3 {
4
public static void
main(String[] args)
5 {
6 Scanner keyboard =
new
Scanner(System.in);
7
8 System.out.println("Enter number of male dancers:");
9
int
men = keyboard.nextInt();
10 System.out.println("Enter number of female dancers: ");
11
int
women = keyboard.nextInt();
(continued)