468
Typical exceptions include IOException,NumberFormatException, and Arithmetic-
Exception.
The throwstatement gives us the ability to throw exceptions when we detect
them. When we create new classes derived from Exception, we can throw exceptions
that are specific to our classes and methods. Those exceptions can then be caught
and handled in ways that are more appropriate than would be possible if we were re-
stricted to using the exception classes in the Java library.
The switchstatement is a multiway selection statement. It allows the code to
choose among a set of branches. A switchstatement containing breakstatements can
always be simulated by an if-then-else-ifstructure. If a switchstatement can be used,
however, it often makes the code easier to read and understand. It cannot be used
with floating-point or string values in the case labels.
The doloop is a general-purpose looping statement. It works like the whileloop
except that its test occurs at the end of the loop, guaranteeing at least one execution
of the loop body. As with a whileloop, a doloop continues as long as the loop
condition remains true.A doloop is a convenient choice for loops that test input val-
ues and then repeat if the input is not correct.
The forstatement is another looping statement and is commonly used to
implement count-controlled loops. The initialization, testing, and incrementation (or
decrementation) of the loop control variable are centralized in one location, the first
line of the forstatement.
The for,do,switch, and throwstatements are the “ice cream and cake” of Java. We
can live without them if we absolutely must, but they are very nice to have. Similarly,
the additional operators that Java supplies, such as +=,%=, and ?:, are sometimes con-
venient shortcuts, but we can program effectively without them. Often, the use of
the less common operators results in code that is more difficult to understand. For
this reason, we recommend that you avoid them. Even so, you must be aware of their
meaning so that you can interpret them when you encounter code written by a pro-
grammer who values compact syntax over clarity.
Quick Check
1.Write a statement that converts a string to an integer and writes out the string
if a NumberFormatErroroccurs. (pp. 432–435)
2.What is the superclass of all exceptions? (pp. 437–438)
3.Given a switch expression that is theintvariablenameVal, write aswitchstate-
ment that writes the following to thePrintWriterfile calledoutData: your first
name ifnameVal= 1, your middle name ifnameVal= 2, and your last name if
nameVal= 3. (pp. 438–442)