try 语句测试代码块的错误。
catch 语句处理错误。
throw 语句创建自定义错误。
catch 块会捕捉到 try 块中的错误,并执行代码来处理它。
<!DOCTYPE html> <html> <head> <script> var txt=""; function message() { try { adddlert("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" οnclick="message()"> </body> </html>
Throw 语句
<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" οnclick="myFunction()">Test Input</button> <p id="mess"></p>