js之错误处理

163 阅读1分钟

上一章 [js语法和数据类型之字面量](https://juejin.cn/post/7090560120634998821)

异常处理语句

throw语句

抛出一个异常,可以抛出一个含有值的表达式

throw (各种类型)表达式
throw 'zifuchuang' // zifuchuang
throw 123 // 123
throw false // false
throw function(){return'cuowo'} 
// function(){return'cuowo'}
throw (function(){return'cuowo'})()
// cuowo
throw {name:'zs'} // {name:'zs'}
在浏览器中会显示未俘获

???备注: 你可以在抛出异常时声明一个对象。那你就可以在catch块中查询到对象的属性。

try...catch语句

标记一块待尝试的语句

try...catch语句中
try{} 代码块可以包含0 or 多条语句,
catch{} 代码块可以有0 or 一个代码块。
  • catch代码块会在try代码块抛出异常时执行,
  • finally代码块会在try,catch之后执行

catch代码块捕获try代码块中第一条错误,之后的错误不会显示

try{
    asdfdsj
    throw '123'
}
catch(e){
    console.log(e) // asdfdsj
}

finally代码块前面的try,catch代码块执行完紧跟着执行,不管后续还是try...catch语句;不管有无异常都会执行,就算没有异常处理也会执行。

该代码块返回一个值,将会是try-catch-finally流程的返回值:

var tcf = function (){
            try{
                throw 123
            }
            catch(e){
                console.log(e) // 123
                return e
            }
            finally{
                return 'isme'
            }
        }
        console.log('tcf',tcf()) // isme

???用finally块覆盖返回值也适用于在catch块内抛出或重新抛出的异常:

???嵌套 try...catch 语句

使用Error对象

使用Error对象抛出的异常,catch捕获后

  • 有name属性 为错误类型名称
  • message属性 为 错误信息
try{
    throw new Error('cuowu')
}
catch(e){
    console.log(e.name) // Error
    console.log(e.message) // cuowo
}