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, Ajax techniques that make use of the XMLHttpRequest object. Unfortunately, this isn’t available in the Internet Explorer. Using the onError event with an alert method pop up 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. Following Example shows how.

<script>
try
{
request = new XMLHTTPRequest()
}
catch(err)
{
// Use a different method to create an XML HTTP Request object
}
</script>

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