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 += "本页有一个错误 "; txt += "错误描述:" + e.message + " "; txt += "点击确定继续。"; alert(txt); } } </script> </head> <body> <button type="button" onclick="message()">查看消息</button> </body> </html>
异常可以是字符串、数字、逻辑值、或对象
1 <script> 2 function myFunction() 3 { 4 try 5 { 6 var x=document.getElementById("demo").value; 7 if(x=="") throw "empty"; 8 if(isNaN(x)) throw "not a number"; 9 if(x>10) throw "too high"; 10 if(x<5) throw "too low"; 11 } 12 catch(err) 13 { 14 var y=document.getElementById("mess"); 15 y.innerHTML="Error: " + err + "."; 16 } 17 } 18 </script> 19 20 <h1>My First JavaScript</h1> 21 <p>Please input a number between 5 and 10:</p> 22 <input id="demo" type="text"> 23 <button type="button" onclick="myFunction()">Test Input</button> 24 <p id="mess"></p>