Java Reference
In-Depth Information
If an exception is thrown at any point during the execution of
the
try
block, control is immediately transferred to the appropri-
ate catch handler if it is present. That is, control transfers to the
first
catch
clause whose exception class corresponds to the excep-
tion that was thrown. After executing the statements in the
catch
clause, control transfers to the statement after the entire
try-catch
statement.
Let's look at an example. Suppose a hypothetical company uses codes to rep-
resent its various products. A product code includes, among other information, a
character in the tenth position that represents the zone from which that product
was made, and a four-digit integer in positions 4 through 7 that represents the
district in which it will be sold. Due to some reorganization, products from zone
R are banned from being sold in districts with a designation of 2000 or higher.
The program shown in Listing 11.2 reads product codes from the user and counts
the number of banned codes entered.
KEY CONCEPT
Each
catch
clause handles a particu-
lar kind of exception that may be
thrown within the
try
block.
Try Statement
try
Block
catch
(
Type
Identifier
)
Block
finally
Block
A
try
statement contains a block of code followed by one or more
catch
clauses. If an exception occurs in the
try
block, the code of the cor-
responding
catch
clause is executed. The
finally
clause, if present, is
executed no matter how the
try
block is exited.
Example:
try
{
System.out.println (Integer.parseInt(numString));
}
catch
(NumberFormatException exception)
{
System.out.println ("Caught an exception.");
}
finally
{
System.out.println ("Done.");
}
Search WWH ::
Custom Search