Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^438) | Exceptions and Additional Control Structures
Look at the try-catchin the previous section:
try
{
myAddress = new Address("myName", "Austin", "Texas", 78744);
}
catch(ZipCodeInvalidException zip)
{
// Exception handler
// Print bad ZIP code
System.out.println(zip.getMessge() + " is invalid");
}
In the catchclause, we use getMessageto retrieve the same string that was
used to instantiate the object of class ZipCodeInvalidException.
Whenever you design a class, you should consider whether some error con-
ditions cannot be handled strictly within the class. Exceptions are, as their name
implies, meant to be used for exceptional situations. We recommend using an ex-
ception only when no simple way to handle an error is available.


9.2 Additional Control Statements


The switch Statement


The switchstatement is a selection control structure for multiway branches. A switchis sim-
ilar to nested ifstatements. The value of a switch expression—an integer expression—deter-
mines which of the branches executes. Look at the following example switchstatement:

switch(digit) // The switch expression is (digit)
{
case1 : Statement1; // Statement1 executes if digit is 1
break; // Go to Statement5
case2 :
case3 : Statement2; // Statement 2 executes if digit is 2 or 3
break; // Go to Statement5
case4 : Statement3; // Statement3 executes if digit is 4
break; // Go to Statement5
default : Statement4; // Execute Statement4 and go to Statement5
}
Statement5; // Always executes

In this example,digitis the switch expression. The statement means, “If digitis 1, execute
Statement1 and break out of the switchstatement and continue with Statement5. If digitis
2 or 3, execute Statement2 and continue with Statement5. If digitis 4, execute Statement3

Switch expression The
expression whose value deter-
mines which switchlabel is se-
lected. It must be an integer
type other than long.
Free download pdf