try { foo.bar();} catch (e) { alert(e.name + ": " + e.message);}
目前我们可能得到的系统异常主要包含以下6种:
- EvalError: raised when an error occurs executing code in eval()
- RangeError: raised when a numeric variable or parameter is outside of its valid range
- ReferenceError: raised when de-referencing an invalid reference
- SyntaxError: raised when a syntax error occurs while parsing code in eval()
- TypeError: raised when a variable or parameter is not a valid type
- URIError: raised when encodeURI() or decodeURI() are passed invalid parameters
new Error();new Error("异常信息");
手工抛出异常的方法如下:
try { throw new Error("Whoops!");} catch (e) { alert(e.name + ": " + e.message);}
如要判断异常信息的类型,可在catch中进行判断:
try { foo.bar();} catch (e) { if (e instanceof EvalError) { alert(e.name + ":" + e.message); } else if (e instanceof RangeError) { alert(e.name + ": " + e.message); } // etc }
Error具有下面一些主要属性:
- description: 错误描述 (仅IE可用).
- fileName: 出错的文件名 (仅Mozilla可用).
- lineNumber: 出错的行数 (仅Mozilla可用).
- message: 错误信息 (在IE下同description)
- name: 错误类型.
- number:&nb