haiyupeter 发表于 2013-2-7 20:36:59

JavaScript异常处理

<div class="iteye-blog-content-contain" style="font-size: 14px;">JavaScript异常处理

浏览器上,使用window.onerror监听错误
 
1.window.onerror的使用
<html><head>    <script type="text/javascript">      function errortest (sMessage, sURL, sLine){            var errorMessage = "IE错误\n";      errorMessage += "错误信息:" + sMessage + "\n";      errorMessage += "链接:" + sURL + "\n";      errorMessage += "行号:" + sLine;      alert(errorMessage);      //window.onerror = null;      return true;      }      window.onerror = errortest;      function test(){      dsfdss      }    </script></head><body ></body></html>       
通过这个例子,提供给我们对页面调试的可能。
分析:

http://dl.iteye.com/upload/attachment/335311/283089e4-c9f2-393b-9eb0-0aa5a80085d9.jpg
 
onerror方法的三个参数:错误信息,链接和行号
在IE下提示,错误信息不够具体,行号经常不准确,目前已很少使用。

目前捕获异常的方式一般为:
try{
} catch(e){
} finally{
}


2. try {} catch (e) {} finally{}
语法和Java相同。
catch参数 e 为 Error 对象,包含属性:name和message
Error对象有多种类型:EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError。
 
<html><head>    <script type="text/javascript">         function test(){      try{      dsfdss      }catch(e){    var errorMessage = "发生了脚本运行错误:\n";    errorMessage += "错误名称:" + e.name + "\n";    errorMessage += "错误信息:" + e.message;    alert(errorMessage);    }    }    </script></head><body ></body></html>如果需要判断E的类型,可以使用
E instanceof TypeError 或者是使用 E.name == "TypeError"
页: [1]
查看完整版本: JavaScript异常处理