1. 程式人生 > >JS中try.. catch..的用法

JS中try.. catch..的用法

 

 

try 測試程式碼塊的錯誤。

catch 語句處理錯誤。

throw 建立並跑出錯誤。

 try
   {
   //在這裡執行程式碼
     丟擲錯誤
   }
 catch(err)
   {
   //在這裡處理錯誤
   }

下面是一個例項:

<p>請輸出一個 5 到 10 之間的數字:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">測試輸入</button>
<p id="mess"></p>

</body>
</html>
<script type="text/javascript">
    function myFunction(){
    try{ 
        var x=document.getElementById("demo").value;   取元素的值
        
        if(x=="")    throw "值為空";       根據獲取的值,丟擲錯誤
        if(isNaN(x)) throw "不是數字";
        if(x>10)     throw "太大";
        if(x<5)      throw "太小";
    }
    catch(err){
        var y=document.getElementById("mess");     抓住上面throw丟擲的錯誤,給p標籤顯示
        y.innerHTML="錯誤:" + err + "。";
    }
}
</script>

try 測試程式碼塊的錯誤。

catch 語句處理錯誤。

throw 建立並跑出錯誤。

 try
   {
   //在這裡執行程式碼
     丟擲錯誤
   }
 catch(err)
   {
   //在這裡處理錯誤
   }

下面是一個例項:

<p>請輸出一個 5 到 10 之間的數字:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">測試輸入</button>
<p id="mess"></p>

</body>
</html>
<script type="text/javascript">
    function myFunction(){
    try{ 
        var x=document.getElementById("demo").value;   取元素的值
        
        if(x=="")    throw "值為空";       根據獲取的值,丟擲錯誤
        if(isNaN(x)) throw "不是數字";
        if(x>10)     throw "太大";
        if(x<5)      throw "太小";
    }
    catch(err){
        var y=document.getElementById("mess");     抓住上面throw丟擲的錯誤,給p標籤顯示
        y.innerHTML="錯誤:" + err + "。";
    }
}
</script>