美文网首页
try和catch

try和catch

作者: tency小七 | 来源:发表于2019-02-18 16:57 被阅读0次

    http://www.runoob.com/jsref/jsref-try-catch.html
    http://www.runoob.com/js/js-errors.html
    之前写代码的时候一直都没有用到try...catch,刚好在上课时候用到了,就顺便来学习一下。

    在下面的例子中,我们故意在 try 块的代码中写了一个错字。

    该实例本应该提醒"欢迎光临!",但弹出的是拼写错误信息。

    catch 块会捕捉到 try 块中的错误,并执行代码来处理它:

        <p>请输入 5 和 10 之间的一个数:</p>
    
        <input id="demo" type="text">
        <button type="button" onclick="myFunction()">检测输入</button>
        <p id="message"></p>
         
        <script>
        function myFunction() {
            var message, x;
            message = document.getElementById("message");
            message.innerHTML = "";
            x = document.getElementById("demo").value;
            try { 
                if(x == "")  throw "为空";
                if(isNaN(x)) throw "不是一个数字";
                if(x > 10)   throw "太大了";
                if(x < 5)    throw "太小了";    
            }
            catch(err) {
                message.innerHTML = "输入的值 " + err;
            }
        }
    

    语法

    try {
        tryCode - 尝试执行代码块
    }
    catch(err) {
        catchCode - 捕获错误的代码块
    } 
    finally {
        finallyCode - 无论 try / catch 结果如何都会执行的代码块
    }
    

    相关文章

      网友评论

          本文标题:try和catch

          本文链接:https://www.haomeiwen.com/subject/qlxzeqtx.html