JavaScript语言 Error对象及错误处理机制 原生错误类型
Error实例对象
JavaScript解析或运行时,一旦发生错误,引擎就会抛出一个错误对象。
JavaScript原生提供Error构造函数,所有抛出的错误都是这个构造函数的实例。
JavaScript语言标准只提到,Error实例对象必须有message属性,表示出错时的提示信息,没有提到其他属性。因此:message:错误提示信息;name:错误名称(非标准属性);stack:错误的堆栈(非标准属性),stack属性用来查看错误发生时的堆栈。
const error = new Error('错误');
console.log(error.message) // "错误"
console.log('error.name = ', error.name); // Error
console.log('error.stack = ', error.stack); // Error: 错误
错误处理机制
try-catch语句,捕获和处理异常的常见方式,它允许在try块中执行可能引发异常的代码,并在 catch块中处理异常。
finally块中的代码始终会被执行,无论是否发生异常,通常用于确保资源的释放或清理工作。
try {// 可能抛出错误的代码throw new Error("This is a generic error");
} catch (error) {// 捕获错误并进行处理console.error(error.message);
} finally {// 在发生异常或未发生异常时都执行的代码console.log("Finally block executed");
}
async function checkAge(age) {if (age < 18) {throw new Error("年龄必须大于或等于18岁!");}return "年龄符合要求!";
}async function exec(age) {try {let result = await checkAge(age);console.log(result);} catch (error) {console.log('e instanceof Error ', error instanceof Error);console.log('error.name = ', error.name); // 错误名称(非标准属性)console.log('error.stack = ', error.stack); // 错误的堆栈(非标准属性)console.log(error.message); // 输出:年龄必须大于或等于18岁}finally{console.log('始终会被执行.');}
}exec(12);
原生错误类型
SyntaxError对象是解析代码时发生的语法错误。
try {eval("Hello World");
} catch (error) {if (error instanceof SyntaxError) {console.error("SyntaxError:", error.message);} else {console.error("Other Error:", error.message);}
}
ReferenceError对象是引用一个不存在的变量时发生的错误。
try {console.log() = 1
} catch (error) {if (error instanceof ReferenceError) {console.error("ReferenceError:", error.message);} else {console.error("Other Error:", error.message);}
}
RangeError对象是一个值超出有效范围时发生的错误。
try {new Array(-1);
} catch (error) {if (error instanceof RangeError) {console.error("RangeError:", error.message);} else {console.error("Other Error:", error.message);}
}
TypeError对象是变量或参数不是预期类型时发生的错误。
try {new 123;
} catch (error) {if (error instanceof TypeError) {console.error("TypeError:", error.message);} else {console.error("Other Error:", error.message);}
}
URIError对象是 URI 相关函数的参数不正确时抛出的错误,主要涉及encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()这六个函数。
try {decodeURI('%2')
} catch (error) {if (error instanceof URIError) {console.error("URIError:", error.message);} else {console.error("Other Error:", error.message);}
}