try-catch语句的嵌套

本文详细探讨了JavaScript中嵌套try-catch-finally语句的行为,包括无内层catch、有内层catch及内层catch再次抛出异常三种情况,并解释了每种情况下异常处理的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

demo1:嵌套try,内层中没有catch语句

  try{
        try {
          throw new Error("opps")
        }
        finally {
          console.log("finally");
        }
      }
      catch(ex){
        console.error("outer",ex.message);
      }
      //弹出 finally
          //outer opps
    //   原因:最外部的try语句块中嵌套了一个try-finally语句,内部的try语句中抛出了一个异常,
    // 但是内部没有catch语句块,所以会执行最近的一个catch语句块,但是在跳出外部try包含语句块之前,
    // 需要先执行内部的finally语句块中的代码,所以最后的结果如上图所示

demo2:嵌套try,但内层有catch

try{
        try {
          throw new Error("opps")
        }
        catch(ex){
          console.error("inner",ex.message);
        }
        finally {
          console.log("finally");
        }
      }
      catch(ex){
        console.error("outer",ex.message);
      }
      //弹出 inner opps
      //     finally
      //原因:这个例子中,内部嵌套的语句块中有catch语句,所以当内部try语句块中抛出异常时,
      // 会接着执行内部的catch语句块,然后执行finally子句

demo3:嵌套try,但内层有catch且在内层catch再throw

  try{
        try {
          throw new Error("opps")
        }
        catch(ex){
          console.error("inner",ex.message);
          throw(ex);
        }
        finally {
          console.log("finally");
        }
      }
      catch(ex){
        console.error("outer",ex.message);
      }
      //弹出 inner opps
      //     finally
      //     outer opps
      //原因:这个例子在上面例子的基础上,内部的catch语句块中又抛出了一个异常,
      // 所以,在执行完相应语句后,会接着执行外部的catch语句,结果如上所示。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值