21 错误处理与调试
- trycatch 异常捕获
javascript
try{
//正常状态执行
console.log(wewewe)
}catch(error){
//所有浏览器都有 message属性
console.log(error.message) //wewewe is not defined
}finally{
//最终都会被执行
console.log('最后都被执行了 不论是否被catch')
}
场景用法
- 在某个第三方库中存在 不致命的 错误(无法修改) ,可以使用trycatch方法来进行 包裹
- 若明确知道代码错误 这样就不再适合 用trycatch了
错误类型 8种
- Error
- syntaxError
- URIError //只会在 encodeURI() 或者 decodeURI 传入格式错误时候发生 很少见
- TypeError //类型错误
- ReferenceError //引用错误
Error是基类型
抛出错误throw
统一的错误处理函数 减轻代码冗余
javascriptfunction assert(condition,message){ if(!condition) { throw new Error(message) } }