↑
Main Page
Handling Errors
It is possible to have the JavaScript console come up whenever there is an error by going into Tools
?
Preferences, and then clicking on Multimedia. You’ll see a check box titled Enabled JavaScript, along with
a button labeled JavaScript Options..... If you click the button, a new dialog pops up (see Figure 14-9), one
of the options is Open JavaScript Console on Error. When this check box is checked (it is unchecked by
default), the JavaScript console pops up whenever there is an error.
Figure 14-9
Handling Errors
Understanding errors is just part of the solution; understanding how to handle those errors is the other
part. Instead of using multiple
if..else
statements, JavaScript offers two specific ways to handle
errors. The Browser Object Model includes the
onerror
event handler on both the window object and
on images, whereas ECMAScript defines the
try...catch
construct, another statement borrowed from
Java, to deal with exceptions. This section outlines the advantages and disadvantages of each approach.
The onerror event handler
The
onerror
event handler was the first feature to facilitate error handling for JavaScript. The
error
event is fired on the
window
object whenever an exception occurs on the page. Example:
<html>
<head>
<title>OnError Example</title>
<script type=”text/javascript”>
window.onerror = function () {
alert(“An error occurred. “);
}
</script>
</head>
<body onload=”nonExistentFunction()”>
</body>
</html>
419
Error Handling
17_579088 ch14.qxd 3/28/05 11:41 AM Page 419
Free JavaScript Editor
Ajax Editor
©
→