Java Reference
In-Depth Information
Display 9.3
Same Thing Using Exception Handling
(part 3 of 3)
Sample Dialogue 3
Enter number of male dancers:
0
Enter number of female dancers:
5
Lesson is canceled. No men.
Sample Dialogue 4
Enter number of male dancers:
4
Enter number of female dancers:
0
Lesson is canceled. No women.
Exception Classes
There are more exception classes than just the single class
Exception
. There are more
exception classes in the standard Java libraries and you can define your own. All the
exception classes in the Java libraries have—and the exception classes you define should
have—the following properties:
• There is a constructor that takes a single argument of type
String
.
• The class has an accessor method
getMessage()
that can recover the string given as
an argument to the constructor when the exception object was created.
try-throw-catch
When used together, the
try
,
throw
, and
catch
statements are the basic mechanism
for throwing and catching exceptions. The
throw
statement throws the exception. The
catch
block catches the exception. The
throw
statement is normally included in a
try
block. When the exception is thrown, the
try
block ends and then the code in the
catch
block is executed. After the
catch
block is completed, the code after the
catch
block(s) is
executed (provided the
catch
block has not ended the program or performed some other
special action).
If no exception is thrown in the
try
block, then after the
try
block is completed, program
execution continues with the code after the
catch
block(s). (In other words, if no exception
is thrown, the
catch
block(s) are ignored.)
(continued)