Java Reference
In-Depth Information
Nested try…catch Statements
So far you've been using just one
try...catch
statement, but it's possible to include a
try...catch
statement inside another
try
statement. Indeed, you can go further and have a
try...catch
inside
the
try
statement of this inner
try...catch
, or even another inside that, the limit being what it's
actually sensible to do.
So why would you use nested
try...catch
statements? Well, you can deal with certain errors inside
the inner
try...catch
statement. If, however, you're dealing with a more serious error, the inner
catch
clause could pass that error to the outer
catch
clause by throwing the error to it.
Here's an example:
try {
try {
ablurt("This code has an error");
} catch(exception) {
var name = exception.name;
if (name == "TypeError" || name == "ReferenceError") {
alert("Inner try...catch can deal with this error");
} else {
throw exception;
}
}
} catch(exception) {
alert("The inner try...catch could not handle the exception.");
}
In this code you have two
try...catch
pairs, one nested inside the other.
The inner
try
statement contains a line of code that contains an error. The
catch
statement of the
inner
try...catch
checks the value of the error's name. If the exception's name is either
TypeError
or
ReferenceError
, the inner
try...catch
deals with it by way of an
alert
box (see Appendix B
for a full list of error types and their descriptions). Unfortunately, and unsurprisingly, the type of
error thrown by the browser depends on the browser itself. In the preceding example, IE reports the
error as a
TypeError
whereas the other browsers report it as a
ReferenceError
.
If the error caught by the inner
catch
statement is any other type of error, it is thrown up in the air
again for the
catch
statement of the outer
try...catch
to deal with.
finally Clauses
The
try...catch
statement has a
finally
clause that defines a block of code that always executes—
even if an exception wasn't thrown. The
finally
clause can't appear on its own; it must be after a
try
block, which the following code demonstrates:
try {
ablurt("An exception will occur");
} catch(exception) {
alert("Exception occurred");
} finally {
alert("This line always executes");
}