The final layer is the web browser, which may display an unpleasant error message to your
visitor, depending on how it??™s configured.
Using the try-catch syntax, you can catch the exception and handle it locally so that the
error won??™t be propagated to the user??™s browser. The try-catch syntax is as follows:
try
{
// Code that might generate an exception
}
catch (e)
{
// Execution is passed to this block when an exception is thrown in the try block
// (exception details are available through the e parameter)
}
If an error happens while executing the code inside the try block, the execution is passed
immediately to the catch block. If no error happens inside the try block, then the code in the
catch block never executes.
The way you handle each exception depends very much on the situation at hand. Sometimes
you will simply ignore the error; other times you will flag it somehow in the code, or you
will display an error message to your visitor. In our particular case, when we want to create an
XMLHttpRequest object, we will first try to create the object as if it were a native browser object,
like this:
CHAPTER 13 ?– IMPLEMENTING AJAX FEATURES 403
// Try to instantiate the native XMLHttpRequest object
try
{
// Create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
Internet Explorer 7, Firefox, Opera, Safari, and other browsers will execute this piece of
code just fine, and no error will be generated, because XMLHttpRequest is supported natively.
Pages:
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517