Summary | 467
cause exceptions to occur, and the expected results from handling them must be speci-
fied.
Testing and Debugging Hints
1.Make sure that all exceptions are either caught or forwarded as appropriate.
2.In a switchstatement, make sure that a breakstatement appears at the end of
each case alternative. Otherwise, control “falls through” to the code in the
next case alternative.
3.Case labels in a switchstatement consist of values, not variables. They may,
however, include named constants and expressions involving only constants.
4.A switch expression must be one of the types char,byte,short, or int. It cannot
be of type longor a floating-point or string expression.
5.The case constants of a switchstatement cannot be of type longor be floating-
point or string constants.
6.If the possibility exists that the value of the switch expression might not
match one of the case constants, you should provide a defaultalternative.
7.Double-check longswitchstatements to make sure that you haven’t omitted
any branches.
8.The doloop is a posttest loop. If the possibility exists that the loop body might
be skipped entirely, use a whileor forstatement.
9.The forstatement heading (the first line) always has three parts within the
parentheses. Typically, the first part initializes a loop control variable, the sec-
ond part tests the variable, and the third part increments or decrements the
variable. The three parts must be separated by semicolons. Any of the parts
can be omitted, but the semicolons still must be present.
Summary
An exception occurs when an error condition is encountered in a method and the
method cannot directly resolve the problem. The method is said to “throw an excep-
tion,” which we can catch using a trystatement. Catching an exception and handling
it properly enables the application to continue executing, rather than allowing the
error to be passed to the JVM, which halts the application with an error message.