JS笔记《错误处理》

105 阅读2分钟

Error实例对象

JS提供了Error构造函数,所有抛出的错误都是这个构造函数的实例。

var err = new Error('测试Error');
err.name        // 错误名称:Error
err.message     // 错误提示信息:'测试Error'

console.log(1); // 1
throw err;
console.log(2); // 不会输出

抛出Error实例对象后,整个程序就中断在抛出错误的地方,不再执行。

原生错误类型

  • 在Error基础上,JS还定义了其他6种错误对象,这6种错误对象都是Error的派生对象。
var syntaxErr = new SyntaxError();
console.log(syntaxErr.__proto__ === SyntaxError.prototype);        // true
console.log(SyntaxError.prototype.__proto__ === Error.prototype);  // true

SyntaxError对象

  • 解析代码时发生的语法错误。
var 1a;      // 变量名错误:Uncaught SyntaxError: Invalid or unexpected token
console.log 'hello')  // 缺少括号:Uncaught SyntaxError: Unexpected string

ReferenceError对象

  • 引用一个不存在的变量时发生的错误。
a      // 使用一个不存在的变量:Uncaught ReferenceError: a is not defined
console.log() = 1    // 将一个值分配给无法分配的对象:Uncaught ReferenceError: Invalid left-hand side in assignment

RangeError对象

  • 一个值超出有效范围时发生的错误。
new Array(-1)  // RangeError: Invalid array length

TypeError对象

  • 变量或参数不是预期类型时发生的错误。
new 123  // Uncaught TypeError: 123 is not a constructor

var obj = {};
obj.a();  // Uncaught TypeError: obj.a is not a function

URIError对象

  • 是URI相关函数的参数不正确时抛出的错误,主要涉及encodeURI()decodeURI()encodeURIComponent()decodeURIComponent()escape()unescape()这六个函数。
decodeURI('%2')  // URIError: URI malformed

EvalError 对象

  • eval函数没有被正确执行时,会抛出EvalError错误。该错误类型已经不再使用了,只是为了保证与以前代码兼容,才继续保留。

自定义错误

function RepeatSubmitError(message){
    this.message = message || '禁止重复提交';
    this.error = 'RepeatSubmitError';
}

RepeatSubmitError.prototype = new Error();
RepeatSubmitError.constructor = RepeatSubmitError;

throw new RepeatSubmitError()  // Uncaught RepeatSubmitError {message: '禁止重复提交', error: 'RepeatSubmitError', stack: ...}

throw

  • 中断程序执行,抛出一个错误。实际上 throw可以抛出任何类型的值。
console.log(1)   // 1
throw new Error('test...')  // Uncaught Error: test...
console.log(2)   // 被中断执行

console.log(1)   // 1
throw true       // Uncaught true
console.log(2)   // 被中断执行

try...catch...finally

  • try代码块抛出错误后,catch代码块会进行捕获然后进行处理,finally代码块表示不管是否出现错误,都必须执行。
try{
    throw new Error('发生了错误……');
}catch(e){
    console.log(e.name);      // 'Error'
    console.log(e.message);   // '发生了错误……'
}

try {
    throw new Error('出错了……');
} 
catch(e){
    console.log(e.message);    // '出错了……'
}
finally {
    console.log('完成清理工作');  // '完成清理工作'
}