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 17 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, to ensure compatibility we should use try
and catch
to trap this case and do something else if the function is not available.
Example 14-12 shows
how.
<script> try { request = new XMLHTTPRequest() } catch(err) { // Use a different method to create an XMLHttpRequest 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 or not 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") }