try 語句測試代碼塊的錯誤。 catch 捕捉try中出現的錯誤 throw 拋出異常(異??梢允?javaScript 字符串、數字、邏輯值或對象)
<html><head> <script> function test(){ try{ alertt("lalala"); } catch(err){ alert("捕捉到異常"); } } </script></head><body> <button onclick="test()">測試異常</button></body></html>try中的alert出現拼寫錯誤,于是在catch中捕捉到異常并執行catch中的代碼
<!DOCTYPE html><html><body> <script> function aaa(){ try{ var s=document.getElementById("input").value; if (isNaN(s)) throw "請輸入數字(NaN)"; else if (s == ""|| s==null) throw "請輸入值(null)"; else if(s>10) throw "大了"; else throw "小了"; } catch(err){ var result = document.getElementById("result"); result.innerHTML = err; } } </script> <p>input a num:</p> <input type="text" id="input"> <button onclick="aaa()">test2</button> <p id="result"></p></body></html>catch捕捉異常err(類似一個var變量),捕捉過后的err的用法類似一個變量。
新聞熱點
疑難解答