O'Reilly logo

Learning PHP, MySQL, and JavaScript by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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")
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required