从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 CATCH try { 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"); }