开发者

try catch in javascript

开发者 https://www.devze.com 2023-01-25 08:16 出处:网络
When i try this code in javascript, why doesn\'t it catch the error on the开发者_如何转开发 misspelling on XMLHttpRequest?

When i try this code in javascript, why doesn't it catch the error on the开发者_如何转开发 misspelling on XMLHttpRequest?

  try {
   var x= new XMLHdfattpRequest();
  } catch (e){
   alert(e);
  }


I've ran this code in Firefox, IE,Chrome and they all caught the error so I assume you mean catch the miss spelling. The reason it wasn't caught is because standard JavaScript is not statically validated like languages such as C#. When the code is executed the name XMLHdfattpRequest has to be checked for in the surrounding lexical scope. If it isn't found it becomes an unresolvable reference. When you try to new up an unresolvable reference that is when a reference error occurs.


May you have some javascript error code before this ?
It can break you browser interpretor and never run you try/catch code.


I've tested the above in both FF 3.5.9 and IE 8 and they behave as expected with an alert popping up. FF with the Firebug plugin turned on also shows the alert.

As others have stated, trying to create a new XMLHdfattpRequest is going to give you a ReferenceError in FF or a TypeError in IE which is definitely supposed to be caught by the catch block.

It seems then, that the problem lies with your browser, or your JavaScript interpreter. It may be bone-headed (I apologise for being so basic in my answer) but have you checked that JavaScript is actually enabled? After all, when you have eliminated the impossible, whatever remains, however improbable, must be the truth.

0

精彩评论

暂无评论...
验证码 换一张
取 消