JS内置错误对象
错误对象是一种特殊的基本对象。它们拥有基本的 Error
类型,同时也有多种具体的错误类型
Error
AggregateError
EvalError
InternalError
RangeError
ReferenceError
SyntaxError
TypeError
URIError
Error
AggregateError
EvalError
InternalError
RangeError
ReferenceError
SyntaxError
当Javascript语言解析代码时,Javascript引擎发现了不符合语法规范的tokens或token顺序时抛出SyntaxError
.try {
eval('hoo bar');
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message); // "missing ; before statement"
console.log(e.name); // "SyntaxError"
console.log(e.fileName); // "Scratchpad/1"
console.log(e.lineNumber); // 1
console.log(e.columnNumber); // 4
console.log(e.stack); // "@Scratchpad/1:2:3\n"
}
try {
throw new SyntaxError('Hello', 'someFile.js', 10);
} catch (e) {
console.log(e instanceof SyntaxError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "SyntaxError"
console.log(e.fileName); // "someFile.js"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // "@Scratchpad/2:11:9\n"
}
const func = () =>(return 1)
// Uncaught SyntaxError: Unexpected token 'return
TypeError
URIError
try catch
```javascript function testFinally() { try { return 2; } catch (e) { return 1; } finally { return 0; } }
testFinally() // 返回0 ```