js error 错误处理

(new) Error([message[, fileName[,lineNumber]]])
单独定义Error()错误,函数继续进行

当像函数一样使用 Error 时 -- 如果没有 new,它将返回一个 Error 对象。所以, 仅仅调用 Error 产生的结果与通过new 关键字构造 Error 对象生成的结果相同。 

// this:
const x = Error('I was created using a function call!');
​​​​//与上面一样
const y = new Error('I was constructed via the "new" keyword!');

Error 类型

ReferenceError引用变量不存在错误  obj.a  

TypeError  类型错误

let a=undefined |null
a.name

let num={}
num.fn()

SyntaxError 语法错误 let num=10++2

出现错误,代码不会执行的情况:1.触发了常见内置错误ReferenceError、TypeError ...2. 主动抛出错误throw Error
出现了错误就需要try-catch捕获错误 代码才会继续向下进行
let a = null
try {
  a.name //error.name=TypeError ;  error.message=Cannot read property 'name' of null(触发内置)
  obj.xxx //error.name=ReferenceError ;  error.message=obj is not defined (触发内置)

} catch (error) {
  console.log(error.message, error.name);//error.message错误信息 ,error.name错误类型

}



function permit(age) {
  if (age > 18) {
    console.log('permission');

  } else {
    throw new Error('age is less 18 ,you have not right') //自己主动抛错误
  }
}

try {
  permit(3)
} catch (error) {
  console.log(error.name, error.message); //error.name=Error; error.message=age is less 18 ,you have not right
}

猜你喜欢

转载自www.cnblogs.com/xiaoliziaaa/p/13194456.html