Using try...catch

The try and catch keywords are more standard and more flexible than the onError technique shown in the previous section. These keywords let you trap errors for a selected section of code, rather than all scripts in a document. However, they do not catch syntax errors, for which you need onError.

The try...catch construct is supported by all major browsers and is handy when you want to catch a certain condition that you are aware could occur in a specific part of your code.

For example, in Chapter 18 we’ll be exploring Ajax techniques that make use of the XMLHttpRequest object. Unfortunately, this isn’t available in the Internet Explorer browser (although it is in all other major browsers). Therefore, we can use try and catch to trap this case and do something else if the function is not available. Example 15-12 shows how.

Example 15-12. Trapping an error with try and catch
<script>
try
{
    request = new XMLHTTPRequest()
}
catch(err)
{
    // Use a different method to create an XML HTTP Request object
}
</script>

I won’t go into how we implement the missing object in Internet Explorer here, but you can see how the system works. There’s also another keyword associated with try and catch called finally that is always executed, regardless of whether an error occurs in the try clause. To use it, just add something like the following statements after a catch statement:

finally
{
    alert("The 'try' clause was encountered")
}

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.