↑
Main Page
The try...catch statement
The try...catch statement
ECMAScript, third edition, introduced another feature from Java, the
try...catch
statement for browsers
that support ECMAScript 3 (see Chapter 1, “What Is JavaScript?”). The basic syntax is the following:
try {
//code to run
[break;]
} catch ([
exception
]) {
//code to run if an exception occurs and the expression is matched
[break;]
} [finally {
//code that is always executed regardless of an exception occurring
}]
For example:
try {
window.nonExistentFunction();
alert(“Method completed. “);
} catch (exception) {
alert(“An exception occurred.”);
} finally {
alert(“End of try...catch test.”);
}
While running a
try...catch
statement, the interpreter first enters the code block immediately after
the
try
keyword. In the previous example, the line
window.nonExistantFunction();
is executed,
which causes an error (because no method named
nonExistantFunction
exists for the
window
object). At
that point, execution immediately exits the
try
clause and goes into the
catch
clause, completely skip-
ping over any further lines of code (the
alert(“Method completed.”);
line is skipped). The
alert
in the catch clause is displayed, and then execution moves into the
finally
clause to display that alert.
Unlike Java, the ECMAScript standard specifies only one catch clause per
try...catch
statement.
Because JavaScript is only loosely typed, you have no way to specify a particular type of exception in
the
catch
clause. All errors, regardless of type, are handled by a single
catch
clause.
The major problem with using the
onerror
event handler is that it is part of the
BOM, and as such, has no standards governing its behavior. To this end, there is a
pretty significant difference between the way browsers handle errors using this
event. For example, when the
error
event occurs in Internet Explorer, normal code
execution continues: All variables and data are retained and remain accessible from
within the
onerror
event handler. In Mozilla, however, normal code execution
ends, and all variables and data existing prior to the error occurring are destroyed,
making it difficult to truly evaluate the error.
Safari and Konqueror do not support the
onerror
event handler on the
window
object but they do support it on images.
423
Error Handling
17_579088 ch14.qxd 3/28/05 11:41 AM Page 423
Free JavaScript Editor
Ajax Editor
©
→