六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 132|回复: 0

JavaScript异常处理

[复制链接]

升级  75.33%

45

主题

45

主题

45

主题

秀才

Rank: 2

积分
163
 楼主| 发表于 2013-2-7 20:36:59 | 显示全部楼层 |阅读模式
<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>       
通过这个例子,提供给我们对页面调试的可能。
分析:


 
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"
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表