Javascript 之错误处理篇

来源:互联网 发布:北拓投资怎么样 知乎 编辑:程序博客网 时间:2024/06/11 15:38

从IE4.0以上的版本,渐渐加入错误处理机制,当然,没有错误处理的代码,不够健壮,所以我在这里不得不班门弄斧,谈谈Javascript中的错误处理。

//noneXistentFunction 引发错误处理机制try{window.noneXistentFunction();alert("Method completed");} catch (exception) {//因为Javascript是弱类型语言,//所以只能有一个catch语句,//并不能分类捕获Exception,//所有的Exception在一个catch中处理alert("an exception occurred" + exception.message);} finally {alert("End of try ... catch test");}//嵌套 TRY CATCHtry {eval("a++b");} catch (exception) {alert("an exception occurrd " + exception.message);try {var aErrors = new Array(100000000000000000000000000000000000000);} catch (exception){alert("another exception occurred");}} finally {alert("all done");}//判断错误类型try {eval("a++b");} catch (exception) {//通过NAME 判断if(exception.name == "SyntaxError") {alert("Syntax Error " + exception.message);} else {alert("An Unexpected Error Occurred " + exception.message);}try {var aErrors = new Array(100000000000000000000000000000000000000);} catch (exception){//通过 INSTANCEOF 判断if(exception instanceof SyntaxError) {alert("Syntax Error " + exception.message);} else if (exception instanceof EvalError){alert("Eval Function Error " + exception.message);} else if (exception instanceof ReferenceError){alert("Reference Error " + exception.message);} else if (exception instanceof RangeError){alert("Number Range Error " + exception.message);} else if (exception instanceof TypeError){alert("variable Type Error " + exception.message);} else if (exception instanceof URIError){alert("encodeURI or decodeURI Function Error " + exception.message);} else {alert("An Unexpected Error Occurred " + exception.message);}}} finally {alert("all done");}
原创粉丝点击