JavaScript学习十三棵--错误

1、try语句测试代码错误

2、catch语句处理错误

3、throw语句创建自定义错误

4、例子:

语法:try

{

运行的代码

}

catch (err)

{

处理错误

}

eg:使用catch处理错误

<DOCUMENT html>

<html>

<head>

<script>

var txt="";

function message()

{

tey{

adddlert("hello");

}

catch(err)

{

txt="There was an error on this page.\n\n";

txt+="Error :"+err.message+"\n\n";

txt+="Click to continue.\n\n";

}

}

</script>

</head>

<bpdy>

<input type="button"value="View message"onclick="message()">

</body>

</html>

下面这个例子创建自定义错误并扑捉错误:

<script>

function myFunction()

{

try{

var x=document.getElementById("demo").value;

if(x=="")  throw "empty";

if(isNaN(x))  throw "not a number";

if(x>10)  throw "too high";

if(x<5)  throw "too low";

}

catch(err)

{

var y=document.getElementById("mess");

y.innerHTML="Error:"+err+".";

}

}

</script>

<h1>My Function</h1>

<p>input between 5 and 10:</p>

<input id="demo" type="text">

<button type="button" onclick="myFunction()">test input</button>

<p id="mess"></p>






































猜你喜欢

转载自blog.csdn.net/u010013191/article/details/41746811