Main Page

Handling syntax errors

Handling syntax errors
The
onerror
event handler isn’t just good for dealing with exceptions; it is also the only way to deal
with syntax errors.
To do so, the event handler must be the first code that appears in the page. Why the first? If a syntax
error occurs before the event handler has been set up, that event handler will never be set up.
Remember, a syntax error completely stops code execution. Consider the following example:
<html>
<head>
<title>OnError Example</title>
<script type=”text/javascript”>
alert(“Syntax error. “;
window.onerror = function (sMessage, sUrl, sLine) {
alert(“An error occurred:\n” + sMessage + “\nURL: “ + sUrl +
“\nLine Number: “ + sLine);
return true;
}
</script>
</head>
<body onload=”nonExistentFunction()”>
</body>
</html>
Because the highlighted line (which is a syntax error) occurs before the
onerror
event handler is
assigned, the browser reports the error directly. The code immediately following the error is not inter-
preted (because the thread is exited) so when the
load
event fires and the
nonExistentFunction()
is
called, the browser reports that error as well. If this page is rewritten to place the
onerror
event-handler
assignment before the syntax error, two alerts are displayed: one showing the syntax error and one
showing the exception.
<html>
<head>
<title>OnError Example</title>
<script type=”text/javascript”>
window.onerror = function (sMessage, sUrl, sLine) {
alert(“An error occurred:\n” + sMessage + “\nURL: “ + sUrl +
“\nLine Number: “ + sLine);
return true;
}
alert(“Syntax error. “;
</script>
</head>
<body onload=”nonExistentFunction()”>
</body>
</html>
422
Chapter 14
17_579088 ch14.qxd 3/28/05 11:41 AM Page 422


JavaScript EditorFree JavaScript Editor     Ajax Editor


©