JavaScript Try...catch语句示例
<html xmlns="http://www.w3.org/1999/xhtml"> <html><title>Try\Catch Statement</title> <head> <script type="text/javascript"> var txt=""; function errormessage() { try { adddlert("JavaScript try catch"); } catch(err) { txt="发生与adddlert相关错误 \n\n"; txt+="Error type: " + err.errormessage + "\n\n"; alert(txt); } } </script> </head> <body> <input type="button" value="error message" onclick="errormessage()" /> </body> </html>
在编程时,开发人员有必要处理由于执行期间的非法操作而在运行时发生的错误或者异常。
例外或者错误的例子:
- 尝试引用一个未定义的变量。
- 调用不存在的方法。
- 语法错误等
Try Catch 语句帮助我们优雅地处理异常。
但它不处理语法错误。
Try...catch语句语法
try { //可能导致错误JavaScript代码 } catch (error) { //处理错误的代码 }
日期:2020-04-18 01:09:33 来源:oir作者:oir