首页 > 其他分享 > try-cathch- finally 捕获错误 throw抛出异常

try-cathch- finally 捕获错误 throw抛出异常

时间:2022-11-29 17:44:48浏览次数:37  
标签:console log err 代码 try finally cathch throw

语法结构 强壮代码 try{ 可能会错的代码 }catch(err){ 捕获错误 }finally{ 不管语法正确错误都会执行 不会影响后面代码的执行 }  

<body>
    <p>123</p>
    <script>
      /* 
   语法结构 强壮代码
   try{
    可能会错的代码
    }catch(err){
    捕获错误
    }finally{
    不管语法正确错误都会执行 不会影响后面代码的执行
    }
    console.log(name);//没声名没赋值 直接报错
 */
      try {
        // 可能会错的代码
        let age = 10;
        debugger;
        // debugger;是一个关键字 相当于控制台直接打断点
        console.log(age);
        console.log(uname);
      } catch (err) {
        // 捕获错误
        console.dir(err);
        alert(err.message);
        // console.log(err);
      } finally {
        console.log("成功失败执行 不管语法正确错误都会执行不会影响后面的代码");
      }
      console.log(1 + 2); //3
    </script>
  </body>
throw抛出异常
<body>
    <script>
      //Error 构造函数(警告提示)throw抛出异常使代码更强壮
      function getSum(x, y) {
        // 表示用户使用不合理
        if (!x || !y) {
          // throw new "你怎么不传参数"();
          throw new Error("你怎么不传参数");
        }
        return x + y;
      }
      console.log(getSum());
    </script>
  </body>

 

标签:console,log,err,代码,try,finally,cathch,throw
From: https://www.cnblogs.com/JAG2671169285/p/16936047.html

相关文章