Java Reference
In-Depth Information
Java syntax: Try-statement
try try-block
catch ( parameter-declaration ) catch-block
finally finally-block
Restrictions : The try-block , catch-block , and finally-block are blocks of the form { … } .
There may be zero or more catch-phrases of the form catch ( parameter-declaration )
{...}. The finally-phrase is optional, unless there is no catch-phrase .
Execution : Discussed in this section. See the CD, lesson page 10.3, for an explanation of
the finally-phrase.
ob , the catch-block catches the thrown ob : ob is assigned to the parame-
ter and the catch-block is executed, after which execution of the try-state-
ment terminates.
2b. If the class of the catch-clause parameter does not match the class of
object ob , Exception ob is thrown to another place. In other words, ob is
handled just as it would have been had there not been a try-statement.
Something is guaranteed to catch the thrown object ob and handle it. Just
how this works is discussed later.
In the example given above, evaluation of 5/x throws an ArithmeticEx-
ception , since x is 0 . This is caught by the catch-block. So the program prints
"x was 0; using 0 for 5 / x", sets y to 0 , and then executes the third statement.
We emphasize that if the try-block does not throw an exception, execution
proceeds normally to the statement following the try-statement. But if the try-
block throws an exception, execution of the try-block is finished. Then, either the
catch-block catches the exception and processes it, after which execution pro-
ceeds to the statement following the try-statement, or the catch-block does not
catch the exception and the thrown object is thrown further —which we explain
later.
/** = the integer in b[f]
-- =-1 if f is outside the range of b ; =0 if b[f] is not an integer */
public int getIntField(String[] b, int f) {
try {
return Integer.parseInt(b[f]);
} catch (ArrayIndexOutOfBoundsException e) {
return -1;
} catch (NumberFormatException e) {
return 0;
}
}
Figure 10.6:
Realistic example of a try-statement
Search WWH ::




Custom Search