目录
常见的内置错误
- Error,所有错误的父类型
所有错误的父类型,一般常被主动用于throw错误输出
- ReferenceError,引用的变量不存在
// ReferenceError
console.log(a) // ReferenceError: a is nor defined
- TypeError,数据类型不正确的错误
// TypeError
let a
console.log(a.xxx) // TypeError: Cannot read property 'xxx' of undefined
a = {}
a.fn() // TypeError: a.fn is not a function
- RangeError,数据值不在其所允许的范围内
// RangeError
function fn() {
fn()
}
fn() // RangeError: Maximum call stack size exceeded
- SyntaxError,语法错误
// SyntaxError
let a = """" // SyntaxError: Unexpected string
错误处理
- 捕获错误: try…catch
正常发生错误,则无法继续往下执行的代码:
// 正常发生错误,则无法继续往下执行的代码
console.log(a) // 此行输出发生错误
console.log(123) // 此行因为上面发生错误,因此未被执行输出
发生错误并捕获,下方代码可正常继续执行:
// try...catch
try {
console.log(a)
} catch (error) { // catch的参数内有两个值,message和stack
console.log(error.message) // message 只输出报错信息
console.log(error.stack) // stack 跟直接输出error本身一致,包含错误类型、错误信息及错误文件
}
console.log(123) // 由于上方代码捕获了错误,因此此行能正常执行输出123
- 抛出错误 throw
// throw
function fn(){
if(Date.now() % 2 === 1){
// 当前时间为奇数
console.log('当前时间为奇数')
}else {
// 当前时间为偶数
throw new Error ('当前时间为偶数')
}
}
try {
fn()
} catch (error) {
alert(error.message)
}
- Recorded by Scorpio_sky@2021-01-25