JavaScript throw語句

來源:互聯網
上載者:User

標籤:

在Javascript try...catch...語句的介紹中,我們知道了如何捕獲系統拋出的錯誤。Javascript允許我們自訂錯誤,並將錯誤資訊拋出。

throw語句

throw 語句允許我們建立自訂錯誤。

正確的技術術語是:建立或拋出異常(exception)。

如果把 throw 與 try 和 catch 一起使用,那麼您能夠控製程序流,並產生自訂的錯誤訊息。

throw語句 文法

throw exception

異常可以是 JavaScript 字串、數字、邏輯值或對象。

在下面的例子中,我們定義了一個除法計算函數,如果函數的被除數是0,則拋出異常。在調用的時候配合try...catch...來處理:

<!DOCTYPE html><html lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>    <meta charset="utf-8" />    <title>JavaScript thorw樣本 - 起飛網</title>    <script type="text/javascript">        //觸發運算        function divsion(num1, num2) {            if (num2 == 0) {                throw "被除數不能為0";            }            return num1 / num2;        }        function btn_click() {            var num1 = Number(document.getElementById("txtNum1").value);            var num2 = Number(document.getElementById("txtNum2").value);            try            {                var result = divsion(num1, num2);                document.getElementById("txtResult").value = result;            }            catch (err) {                alert(err);            }        }    </script></head><body>    <h1>JavaScript thorw樣本 - <a href="http://www.qeefee.com">起飛網</a></h1>    <input type="text" value="6" id="txtNum1" />    <span>÷</span>    <input type="text" value="3" id="txtNum2" />    <span>=</span>    <input type="text" value="" id="txtResult" />    <input type="button" value="計算" onclick="btn_click()" /></body></html>

 

JavaScript throw語句

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.