zoukankan      html  css  js  c++  java
  • try 、catch 、finally 、throw 测试js错误

    try语句允许我们定义在执行时进行错误测试的代码块。

    catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块。

    finally 语句在 try 和 catch 之后无论有无异常都会执行。

    throw 语句创建自定义错误。

    JavaScript 语句 try 和 catch 是成对出现的。

    例子:

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="utf-8">
     5 <title>菜鸟教程(runoob.com)</title>
     6 </head>
     7 <body>
     8 
     9 <p>请输出一个 5 到 10 之间的数字:</p>
    10 
    11 <input id="demo" type="text">
    12 <button type="button" onclick="myFunction()">测试输入</button>
    13 <p id="message"></p>
    14 
    15 <script>
    16 function myFunction() {
    17     var message, x;
    18     message = document.getElementById("message");
    19     message.innerHTML = "";
    20     x = document.getElementById("demo").value;
    21     try { 
    22         if(x == "")  throw "值为空";
    23         if(isNaN(x)) throw "不是数字";
    24         x = Number(x);
    25         if(x < 5)    throw "太小";
    26         if(x > 10)   throw "太大";
    27     }
    28     catch(err) {
    29         message.innerHTML = "错误: " + err;
    30     }
    31 }
    32 </script>
    33 
    34 </body>
    35 </html>
  • 相关阅读:
    素数筛的2种方法
    c++含结构体的sort()使用
    构建c++二维vector
    c语言输入单字符避免回车的四种方法
    menset()在c++中的作用
    杭电oj hud1092 1093 活用EOF&n--
    EOF在while(scanf("%d",&n))中的作用
    KMP算法
    图解HTTP(3)
    图解HTTP(2)
  • 原文地址:https://www.cnblogs.com/ziyoublog/p/9449648.html
Copyright © 2011-2022 走看看