try和catch

2019-02-18  本文已影响0人  tency小七

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 结果如何都会执行的代码块
}
上一篇下一篇

猜你喜欢

热点阅读