知向前端
js 中的常见内置错误及错误处理
2020-5-31 Jon

常见内置错误



Error:所有错误对象的父类型




  1. ReferenceError: 引用的变量不存在



console.log(a) // ReferenceError: a is not defined 



  1. TypeError: 数据类型不正确的错误



let b
console.log(b.xxx) // TypeError: Cannot read property 'xxx' of undefined
b = {}
b.xx() // TypeError: b.xxx is not a function



  1. RangeError: 数据值不在其所允许的范围内



function fn(){
fn();
}
fn() // RangeError: Maximum call stack size exceeded



  1. SyntaxError: 语法错误



let abc = """" // SyntaxError: Unexpected string
console.log(1++2) // SyntaxError: Invalid left-hand side expression in postfix operation



错误处理



程序出现错误如果不对错误进行处理,则报错行后面的代码将无法继续执行。需要捕获处理错误后才能继续执行
错误对象
massage 属性:错误相关信息
stack 属性:函数调用栈记录信息




  1. 捕获异常:try...catch



try {
console.log(bbb)
}catch(error) {
console.log(error)
}



  1. 抛出错误:throw error



   js    14行

function fun() {
if(Math.random()>0.5) {
console.log('模拟正确,继续执行');
}else{
console.log('模拟错误,抛出异常,给外部调用着处理');
throw new Error('出错了')
}
}
try{
fun()
}catch(error){
// 自定义提示
alert(error.massage);
}


发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容