zoukankan      html  css  js  c++  java
  • js 学习之路10:try异常处理和第一个js小程序

    try 语句测试代码块的错误。

    catch 语句处理错误。

    throw 语句创建自定义错误。

    1. try/catch语句

    catch语句用来捕获try代码块中的错误,并执行自定义的语句来处理它。

    语法:

    try
      {
      //在这里运行代码
      }
    catch(err)
      {
      //在这里处理错误
      }
    <!DOCTYPE html>
    <html>
    <head>
    
    <script>
    
    var txt = "";
    function message()
    {
        try
        {
            abcdlert("Welcome guest!");
        }
        catch(err)
        {
            txt = "There was an error on this page.
    
    ";
            txt += "Error description:" + err.message + "
    
    ";
            txt += "Click OK to continue.
    
    ";
            alert(txt);
        }
    }
    </script>
    </head>
    
    <body>
    <input type = "button" value = "View message" onclick = "message()">
    </body>
    </html>

    2. throw语句

    throw语句允许我们创建自定义错误

    示例:

    <!DOCTYPE html>
    <html>
    <body>
    
    <script>
    function myFunction()
    {
    try
    { 
    var x=document.getElementById("demo").value;
    if(x=="")    throw "值为空";
    if(isNaN(x)) throw "不是数字";
    if(x>10)     throw "太大";
    if(x<5)      throw "太小";
    }
    catch(err)
    {
    var y=document.getElementById("mess");
    y.innerHTML="错误:" + err + "。";
    }
    }
    </script>
    
    <h1>我的第一个 JavaScript 程序</h1>
    <p>请输入 5 到 10 之间的数字:</p>
    <input id="demo" type="text">
    <button type="button" onclick="myFunction()">测试输入值</button>
    <p id="mess"></p>
    
    </body>
    </html>
  • 相关阅读:
    C++ 纸牌 今日头条面试题
    c++ 病句 今日头条面试题
    C++ 球迷 今日头条面试题
    C++ 活动安排
    C++ 弗洛伊德算法
    填坑 bzoj3337
    bzoj3884 上帝与集合的正确用法
    人参中第一次膜你退货
    洛谷P2216 [HAOI2007]理想的正方形
    洛谷 P1099 树网的核+P2491 [SDOI2011]消防
  • 原文地址:https://www.cnblogs.com/zrmw/p/10364772.html
Copyright © 2011-2022 走看看