Previous Page
Next Page

7.4. JavaScript Exceptions

JavaScript has a number of language features that are useful in the debugging process. The biggest one of these is the ability to catch any JavaScript error as an exception. This is done by wrapping code that can cause errors inside of a try block followed by a catch block. In the catch block, you have access to an Error object, which contains additional information about the error. This Error object contains the name of the error and a message. On Firefox, it also includes the file in which the error happened, the line on which it happened, and a call stack. Listing 7-4 shows an example of catching an error. Listings 7-5 and 7-6 show the output of the catch block in Firefox and IE.

Listing 7-4. exception.html

1  <html>
2  <body>
3        <div id="error">
4        </div>
6  <script type="text/javascript">
7  try {
8     alert(IDontExist);
9  }
10  catch (e) {
11     var msg = '';
12     for(var i in e) {
13       msg += i+':'+e[i]+"<br>\n";
15    }
16    document.getElementById('error').innerHTML = msg;
17  }
18 </script>
19 </body>
20 </html>

Listing 7-4 is simple. It contains a basic HTML page with a JavaScript block that creates the error and then prints out the resulting error object. Lines 34 give us an element to which to write an error message. Line 7 starts the try block; it's ended by the bracket on line 9. All JavaScript errors that happen in the TRy block will cause the catch block to be run. If no error happens, the code in the catch block is ignored. The catch block on lines 1017 takes the error object and prints out each property. This text is then added to the error element, showing the value of the error object.

Listing 7-5. Output of exception.html in Firefox

message:IDontExist is not defined

Listing 7-6. Output of exception.html in Internet Explorer

message:'IDontExist' is undefined
description:'IDontExist' is undefined

Looking at the error messages, you can see that exceptions in Firefox are more useful for general debugging, but exceptions are still useful even without line properties because you end up knowing which block of code caused the error. They also allow you to handle the error programmatically, letting you give the user an error message or even perform a workaround instead of having your code silently break.

Previous Page
Next Page