JavaScript是一门Web编程语言,用来实现网页的交互功能,它和HTML、CSS共同组成了个Web开发的基础工具集合,也是前端开发者必备的技能;学习JavaScript教程可以了解它在网页开发中的所有特性和相关概念,让我们能够更加快速的去开发Web应用。
throw语句用于抛出用户定义的异常。
针对意外事件,你可以自定义异常并通过合理控制脚本流程,在try块中抛出异常并在catch块中进行处理。
语法说明
throw exception;
执行一下代码说明
exception:字符串、整数、布尔值或对象。
以下示例检查名为empcode变量的长度。若empcode的长度大于8或小于3,代码将抛出错误,该错误会被catch语句捕获并显示相应消息。
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript try..catch..throw Example</title>
</head>
<body>
<h1 style="color: red">JavaScript : try..catch..throw Example</h1>
<hr />
<script src="try-catch-throw-example.js"></script>
</body>
</html>
执行一下JS代码
var empcode = prompt("Input the Employee code : (Between 3 to 8 characters):","");
try
{
if(empcode.length>8)
{
throw "error1";
}
else if(empcode.length<3)
{
throw "error2";
}
}
catch(err)
{
if(err=="error1")
{
console.log("The Employee code length exceed 8 characters.");
}
if(err=="error2")
{
console.log("The Employee code length is less than 3 characters");
}
}
执行一下