Jump to content
Larry Ullman's Book Forums

Why Use Try-Catch Syntax For Creating An Ajax Object


Recommended Posts

Larry, if you don't mind me asking, why do you use the try-catch syntax in the function that creates an Ajax object? I ask because I have noticed that a lot of other (similar) functions for creating an Ajax object don't use that notation. Is there any particular benefit? I specifically ask because you don't do anything with the caught exception anyway.

 

Thanks.

Link to comment
Share on other sites

Well, first of all, the book doesn't do everything, so I expect the reader can take what's there, and add what you want to happen when an error occurs. But the other thing is that the try...catch can handle errors in any block of code. If you went if-else, you'd have to do that for every possible thing. Say you have a block of code that involves five steps. With if-else, you'll need to create if-else statements for each of the five steps. With try...catch, you can put all five steps within the try block and catch errors that occur in any of those five steps using the one catch statement.

Link to comment
Share on other sites

Well, I agree with you there, but specifically for the purpose of creating an Ajax object, try-catch just seemed like overkill. But you're right, with try-catch, the user can add extra functionality easily, if necessary.

 

I was looking at w3schools.com's implementation for creating an Ajax object from the following website:

 

http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp

 

Their code is as follows:

 

var xmlhttp;
if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 

Their implementation completely skips out on one of the ActiveXObject types that you test for. What do you think about this method, as compared to yours?

Link to comment
Share on other sites

The code from W3Schools, missing on ActiveXObject is obviously less accommodating, but that one use may be outdated by this point.

 

And thanks for all your help in answering other people's questions. I really appreciate it.

Link to comment
Share on other sites

 Share

×
×
  • Create New...