您的位置:首页 > Web前端 > JavaScript

JavaScript异常错误处理

2015-08-04 16:25 721 查看
1.异常:

当JavaScript引擎执行JavaScript代码时,发生了错误,导致程序停止运行

2.异常抛出:

当异常产生,并且将这个异常生成一个错误信息

3.异常捕获:

try{
发生异常的代码块
}catch(err){
错误信息处理
}


<html>
<head>
<script>
var txt="";
function message(){
try{
addlert("welcome")
}
catch(err){
txt="本页有一个错误异常:"+err.message;
alert(txt);
}
</script>
</head>

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


4.Throw语句通过throw语句创建一个自定义错误

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 First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: