Main Page

Nested try...catch statements

The code in the
finally
clause behaves the same way as the
finally
clause in Java, containing code
that should be executed whether or not an exception occurs. This is useful for closing open connections
and freeing up resources. For instance:
connection.open();
try {
connection.send(data);
} catch (exception) {
alert(“An exception occurred.”);
} finally {
connection.close();
}
Nested try...catch statements
It is possible for an error to occur inside the
catch
clause of a
try...catch
statement. In this case,
using nested
try...catch
statements is the answer. Consider the following example
try {
eval(“a ++ b”); //causes error
} catch (oException) {
alert(“An exception occurred. “);
try {
var aErrors = new Array(10000000000000000000000); //causes error
aErrors.push(exception);
} catch (oException2) {
alert(“Another exception occurred.”);
}
} finally {
alert(“All done.”);
}
In this example, an error is thrown immediately and the first alert is displayed. When execution contin-
ues in the first
catch
clause, another error is thrown because of the attempt to create an array with too
many elements. Execution goes to the second
catch
clause and displays the second alert before continu-
ing on into the
finally
clause.
The Error object
So what exactly is it that the
catch
statement catches? Just as Java has a base class
Exception
to throw,
JavaScript has a base class called
Error
to throw. An
Error
object has the following properties:
?
name
— A string indicating the type of error
?
message
— The actual error message
Mozilla’s extensions to ECMAScript include the capability to add more than one
catch clause per
try...catch
statement. However, because this extension exists
only in Mozilla, it is not recommended.
424
Chapter 14
17_579088 ch14.qxd 3/28/05 11:41 AM Page 424


JavaScript EditorFree JavaScript Editor     Ajax Editor


©