try:语句测试代码块的错误,当try中的代码块出错时执行catch中的代码块。
catch:语句处理错误;
throw:语句创建或抛出自定义异常。
三者一起使用可以控制程序流并生成自定义异常信息。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>just test</title> <script>
var txt = "";
function message()
{
try
{
adddlert("welcome guest!");
}
catch(e)
{
txt += "本页有一个错误\n\n";
txt += "错误描述:" + e.message + "\n\n";
txt += "点击确定继续。";
alert(txt);
}
}
</script>
</head>
<body>
<button type="button" onclick="message()">查看消息</button>
</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 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>