除了通用的Error构造函数外,JavaScript还有6个其他类型的错误构造函数。它们会在特殊时刻,或由特定的对象触发。
2. JS中的错误类型
2.1 EvalError - Eval错误
eval()
是全局对象的一个函数属性。
eval()
的参数是一个字符串。如果字符串表示的是表达式,eval()
会对表达式进行求值。如果参数表示一个或多个 JavaScript 语句,那么
eval()
就会执行这些语句。不需要用
eval()
来执行一个算术表达式:因为 JavaScript 可以自动为算术表达式求值。
EvalError
对象表示全局函数eval()
中发生的错误。如果eval()
中没有错误,则不会抛出该错误。
如:抛出一个EvalError
异常:
try {
throw new EvalError('eval()发生错误了');
} catch (e) {
console.log(e instanceof EvalError); // true
console.log(e.message); // "eval()发生错误了"
console.log(e.name); // "EvalError"
console.log(e.stack); // "EvalError: eval()发生错误了"
}
2.2 ReferenceError - 引用错误
RHS 查询在所有嵌套的作用域中遍寻不到所需的变量,引擎就会抛出 ReferenceError
异常。
例如:引用为定义变量,会抛出该异常
try {
var a = b; // b从未定义
} catch (e) {
console.log(e instanceof ReferenceError); // true
console.log(e.message); // "b is not defined"
console.log(e.name); // "ReferenceError"
console.log(e.stack); // "ReferenceError: b is not defined"
}
2.3 RangeError - 范围错误
RangeError
错误对象会在值超过有效范围时触发。
触发RangeError
错误的情况有:对Array
构造函数使用错误的长度值,对Number.toExponential()
、Number.toFixed()
或Number.toPrecision()
使用无效数字等。
try {
var num = 120.56
num.toFixed(-1)
} catch (e) {
console.log(e instanceof RangeError); // true
console.log(e.message); // "toFixed() digits argument must be between 0 and 100"
console.log(e.name); // "ReferenceError"
console.log(e.stack); // "ReferenceError: toFixed() digits argument must be between 0 and 100"
}
2.4 SyntaxError - 语法错误
JS语法错误时触发,属于比较常见的错误
可以像下面这样创建并捕获语法错误:
try {
throw new SyntaxError('Hello');
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "SyntaxError"
}
2.5 TypeError - 类型错误
TypeError
错误会在对象用来表示值的类型非预期类型时触发。
例如:当对一个非函数变量,使用函数调用时,会抛出该异常
try {
var num = 123;
num()
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // "num is not a function"
console.log(e.name); // "TypeError"
console.log(e.stack); // "TypeError: num is not a function"
}
2.6 URIError - URI错误
URIError
错误会错误使用全局URI函数如encodeURI()
、decodeURI()
等时触发。也可以通过构造函数创建该对象的实例:
new TypeError([message])
可以像下面这样捕获URI错误:
try {
decodeURIComponent('%');
} catch (e) {
console.log(e instanceof URIError); // true
console.log(e.message); // "URI malformed"
console.log(e.name); // "URIError"
}