如何在 JavaScript 中捕捉異常?


若要在 JavaScript 中捕捉異常,請使用 try…catch…finally。JavaScript 實現 try...catch...finally 構造以及 throw 運算子來處理異常。

你可以捕捉程式設計師生成的和執行時異常,但無法捕捉 JavaScript 語法錯誤。

示例

你可以嘗試執行以下程式碼,瞭解如何在 JavaScript 中捕捉異常 −

 線上演示

<html>
   <head>
      <script>
         <!--
            function myFunc() {
               var a = 100;
               try {
                  alert("Value of variable a is : " + a );
               }
               catch ( e ) {
                  alert("Error: " + e.description );
               }
               finally {
                  alert("Finally block will always execute!" );
               }
            }
         //-->
      </script>
   </head>

   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>

更新於: 2020 年 1 月 16 日

280 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.