throw 语句允许我们创建自定义错误。

正确的技术术语是:创建或抛出异常(exception)。

如果把 throw 与 try 和 catch 一起使用,那么您能够控制程序流,并生成自定义的错误消息。

语法

throw exception

异常可以是 JavaScript 字符串、数字、逻辑值或对象。

实例

本例检测输入变量的值。如果值是错误的,会抛出一个异常(错误)。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 >
<button type="button" onclick="myFunction()">Test Input</button>
<p ></p>

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-13
  • 2022-02-08
  • 2022-12-23
  • 2021-10-03
  • 2021-07-05
  • 2021-11-12
  • 2022-12-23
相关资源
相似解决方案