JavaScript学习与实践(14)
这个语句可以帮你找出代码块中的错误,并避免错误
老习惯,先看两个例子
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Welcome guest!")
}
catch(err)
{
txt="There was an error on this page.\n\n"
txt+="Error description: " + err.description + "\n\n"
txt+="Click OK to continue.\n\n"
alert(txt)
}
}
</script>
另外一个例子
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Welcome guest!")
}
catch(err)
{
txt="There was an error on this page.\n\n"
txt+="Click OK to continue viewing this page,\n"
txt+="or Cancel to return to the home page.\n\n"
if(!confirm(txt))
{
document.location.href=http://lxsohu.cnblogs.com/
}
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
JS中捕获错误,当页面在浏览器中的时候,我们常常可以看出,JS弹出错误的提示“您是否愿意调试?”错误的提示对开发者来说是好的,但是对用户来说就不是必要的,这样用户往往就离开你当前的页面了,
这节就告诉你怎么捕获和操作错误的信息,让咱们不会失去用户,
这里有两种捕获错误的方法:
1,用try.....catch语句来捕获(在IE5.5+,Mozilla 1.0,Netscape 6)
语法:
try { //Run some code here } catch(err) { //Handle errors here }
注意,他们是用小写字母的,用大写就会出错。
2,用onerror事件,这个是旧的标准解决错误的标准,不过你要是用的话,就要学会throw语句