• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
龙星之峰
抓住时间,改变现状
博客园    首页    新随笔    联系   管理    订阅  订阅

JavaScript学习与实践(14)

JS中的Try...catch语句

   这个语句可以帮你找出代码块中的错误,并避免错误

老习惯,先看两个例子

 

<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语句

 

 

 

posted @ 2007-01-22 16:41  lxsohu  阅读(185)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3