Js 錯誤 - Throw、Try 和 Catch

本例檢測輸入變量的值。如果值是錯誤的,會拋出一個異常(錯誤)。catch 會捕捉到這個錯誤,並顯示一段自定義的錯誤消息:
<script>
function myFunction()
{
try
  {
  var x=document.getElementById("demo").value;
  if(x=="")    throw "empty";
  if(isNaN(x)) throw "not a number";
  if(x>10)     throw "too high";
  if(x<5)      throw "too low";
  }
catch(err)
  {
  var y=document.getElementById("mess");
  y.innerHTML="Error: " + err + ".";
  }
}
</script>

<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" οnclick="myFunction()">Test Input</button>
<p id="mess"></p>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章