↑
Main Page
Debugging Techniques
Note that the check for the
instanceof Error
must be the last condition in the
if
statement because
all the other error classes inherit from it (so a
SyntaxError
returns
true
when testing
instanceof
Error
).
Debugging Techniques
Before JavaScript debuggers were readily available, developers had to use creative methods to debug
their code. This led to the placement of strategically placed alerts, using LiveConnect to access the Java
console, using the JavaScript console, and throwing custom errors. Each of these techniques has its
advantages and disadvantages. Which one should you use? This section explains which debugging tech-
nique is right for you.
Using alerts
The most popular (although the most unwieldy) method of debugging is the placement of alerts strategi-
cally throughout code. For example:
function test_function() {
alert(“Entering function.”);
var iNumber1 = 5;
var iNumber2 = 10;
alert(“Before calculation.”);
var iResult = iNumber1 + iNumber2;
alert(“After calculation.”);
alert(“Leaving function.”);
}
JavaScript developers around the world turn to alerts as a quick and dirty approach for debugging. The
most popular way is to show alerts with descriptive text, as in the previous example. Some also use a
numbering method, starting the first alert at 0, the second at 1, and so on, to see where the code breaks.
This approach requires a lot of cleanup because you must remove the extra alerts when your debugging
is complete. Another problem occurs when dealing with infinite loops: If your script is causing an infi-
nite or long-running loop, alerts could keep popping up and prevent you from closing the browser. For
this reason, using alerts for debugging is best kept to small code segments.
All browsers report a developer-thrown error, but the way the error message is dis-
played may differ slightly. Internet Explorer 6 only displays the error messages
when throwing the
Error
object; otherwise, it simply says
Exception thrown and
not caught
without giving any of the details specified; Mozilla, however, reports
Error: uncaught exception:
and then calls the
toString()
method of the object
that was thrown.
428
Chapter 14
17_579088 ch14.qxd 3/28/05 11:41 AM Page 428
Free JavaScript Editor
Ajax Editor
©
→