JS捕获异常,可使用如下的两种方法
使用 try...catch 语句;(在 IE5+、Mozilla 1.0、和 Netscape 6 中可用)
使用 onerror 事件;这是用于捕获错误的老式方法。(Netscape 3 以后的版本可用)
①Try...Catch 语句
try...catch 可以测试代码中的错误。try 部分包含需要运行的代码,而 catch 部分包含错误发生时运行的代码。
语法介绍:
try
{
//在此运行代码
}
catch(err)
{
//在此处理错误
}
实例介绍:
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Welcome guest!")
}
catch(err)
{
txt="此页面存在一个错误。\n\n"
txt+="错误描述: " + err.description + "\n\n"
txt+="点击OK继续。\n\n"
alert(txt)
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
②onerror 事件
首先您需要学习如何使用 throw 语句来创建异常。throw 语句可以与 try...catch 语句一起使用。
throw语法介绍:
throw(exception)
onerror语法介绍:
onerror=handleErrfunction handleErr(msg,url,l)
{
//Handle the error here
return true or false
}浏览器是否显示标准的错误消息,取决于 onerror 的返回值。如果返回值为 false,则在控制台(JavaScript console) 中显示错误消息。反之则不会。
实例介绍:
下面的例子展示如何使用 onerror 事件来捕获错误:
<html>
<head>
<script type="text/javascript">
onerror=handleErr
var txt=""
function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n"
txt+="Error: " + msg + "\n"
txt+="URL: " + url + "\n"
txt+="Line: " + l + "\n\n"
txt+="Click OK to continue.\n\n"
alert(txt)
return true
}
function message()
{
adddlert("Welcome guest!")
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
建议您还是使用第①种处理异常,第②种已不常用。