简体   繁体   English

尝试赶上JavaScript

[英]try catch in javascript

When i try this code in javascript, why doesn't it catch the error on the misspelling on XMLHttpRequest ? 当我在javascript中尝试此代码时,为什么不捕获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. 我已经在Firefox,IE,Chrome中运行了此代码,它们都捕获了错误,因此我认为您的意思是捕获拼写错误。 The reason it wasn't caught is because standard JavaScript is not statically validated like languages such as C#. 它没有被捕获的原因是因为标准的JavaScript没有像C#这样的语言进行静态验证。 When the code is executed the name XMLHdfattpRequest has to be checked for in the surrounding lexical scope. 执行代码时,必须在周围的词法范围内检查名称XMLHdfattpRequest 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 ? 在此之前,您可能会遇到一些JavaScript错误代码吗?
It can break you browser interpretor and never run you try/catch code. 它可能会破坏您的浏览器解释程序,而不会运行您的try / catch代码。

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 3.5.9和IE 8中测试了以上内容,它们的行为与预期的一样,并弹出一个警报。 FF with the Firebug plugin turned on also shows the alert. 启用了Firebug插件的FF也会显示警报。

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. 正如其他人所述,尝试创建一个新的XMLHdfattpRequest将给您FF中的ReferenceError或IE中的TypeError ,这肯定应该由catch块捕获。

It seems then, that the problem lies with your browser, or your JavaScript interpreter. 这样看来,问题出在您的浏览器或JavaScript解释器上。 It may be bone-headed (I apologise for being so basic in my answer) but have you checked that JavaScript is actually enabled? 它可能是头脑呆板的(我很抱歉在回答中如此基本),但是您是否检查了JavaScript是否已真正启用? After all, when you have eliminated the impossible, whatever remains, however improbable, must be the truth . 毕竟, 当您消除了不可能的事情之后,无论多么不可能的事情,剩下的都是真理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM