当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js 学习之路10:try异常处理和第一个js小程序

js 学习之路10:try异常处理和第一个js小程序

2019年02月13日  | 移动技术网IT编程  | 我要评论
try 语句测试代码块的错误。 catch 语句处理错误。 throw 语句创建自定义错误。 1. try/catch语句 catch语句用来捕获try代码块中的错误,并执行自定义的语句来处理它。 语法: 2. throw语句 throw语句允许我们创建自定义错误 示例: ...

try 语句测试代码块的错误。

catch 语句处理错误。

throw 语句创建自定义错误。

1. try/catch语句

catch语句用来捕获try代码块中的错误,并执行自定义的语句来处理它。

语法:

try
  {
  //在这里运行代码
  }
catch(err)
  {
  //在这里处理错误
  }
<!doctype html>
<html>
<head>

<script>

var txt = "";
function message()
{
    try
    {
        abcdlert("welcome guest!");
    }
    catch(err)
    {
        txt = "there was an error on this page.\n\n";
        txt += "error description:" + err.message + "\n\n";
        txt += "click ok to continue.\n\n";
        alert(txt);
    }
}
</script>
</head>

<body>
<input type = "button" value = "view message" onclick = "message()">
</body>
</html>

2. throw语句

throw语句允许我们创建自定义错误

示例:

<!doctype html>
<html>
<body>

<script>
function myfunction()
{
try
{ 
var x=document.getelementbyid("demo").value;
if(x=="")    throw "值为空";
if(isnan(x)) throw "不是数字";
if(x>10)     throw "太大";
if(x<5)      throw "太小";
}
catch(err)
{
var y=document.getelementbyid("mess");
y.innerhtml="错误:" + err + "。";
}
}
</script>

<h1>我的第一个 javascript 程序</h1>
<p>请输入 5 到 10 之间的数字:</p>
<input id="demo" type="text">
<button type="button" onclick="myfunction()">测试输入值</button>
<p id="mess"></p>

</body>
</html>

 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网