常见错误类型
- Error 所有错误的父类型
- ReferenceError 引用的变量不存在(xx is not defined)
- TypeError 数据类型不正确(a,xx is not a function; Cannot read property xx of undefined)
- RangeError 数据值不在允许的范围内(Maximu call stack size exceeded)
- SyntaxError 语法错误(Unexpected xx)
错误处理
- 捕获错误 try…catch
- 抛出错误 throw error
错误对象
message属性 :错误相关信息
stack属性: 函数调用栈记录信息
捕获系统异常
// try ...catch
try{
let d;
console.log(d.xx);
}catch(error){
console.log(error.message);
console.log(error.stack);
}
console.log('出错后打印的');
运行结果:
捕获throw抛出的异常
function some(){
if(Date.now()%2==1){ //判断当前时间是否为奇数
console.log('时间是奇数,可以执行任务');
}else{ //抛出异常
throw new Error('时间是偶数,任务结束')// Error的()内填message
}
}
//捕获处理错误
try{
some();
}catch(error){
console.log(error);
console.log(error.message);
}
结果如下