JS内置错误对象

错误对象是一种特殊的基本对象。它们拥有基本的 Error 类型,同时也有多种具体的错误类型

  1. Error
  2. AggregateError
  3. EvalError
  4. InternalError
  5. RangeError
  6. ReferenceError
  7. SyntaxError
  8. TypeError
  9. URIError

    Error

    AggregateError

    EvalError

    InternalError

    RangeError

    ReferenceError

    SyntaxError

    当Javascript语言解析代码时,Javascript引擎发现了不符合语法规范的tokens或token顺序时抛出SyntaxError.
    1. try {
    2. eval('hoo bar');
    3. } catch (e) {
    4. console.log(e instanceof SyntaxError); // true
    5. console.log(e.message); // "missing ; before statement"
    6. console.log(e.name); // "SyntaxError"
    7. console.log(e.fileName); // "Scratchpad/1"
    8. console.log(e.lineNumber); // 1
    9. console.log(e.columnNumber); // 4
    10. console.log(e.stack); // "@Scratchpad/1:2:3\n"
    11. }
    1. try {
    2. throw new SyntaxError('Hello', 'someFile.js', 10);
    3. } catch (e) {
    4. console.log(e instanceof SyntaxError); // true
    5. console.log(e.message); // "Hello"
    6. console.log(e.name); // "SyntaxError"
    7. console.log(e.fileName); // "someFile.js"
    8. console.log(e.lineNumber); // 10
    9. console.log(e.columnNumber); // 0
    10. console.log(e.stack); // "@Scratchpad/2:11:9\n"
    11. }
    1. const func = () =>(return 1)
    2. // Uncaught SyntaxError: Unexpected token 'return

    TypeError

    URIError

    try catch

    ```javascript function testFinally() { try { return 2; } catch (e) { return 1; } finally { return 0; } }

testFinally() // 返回0 ```