JavaScript_throw、try和catch

throw 语句创建自定义错误

try 语句测试代码块的错误

catch 语句处理错误

<!DOCTYPE html>
<html>
<head>
<title>17th_test</title>
<meta charset="gb2312">
</head>

<body>
<h1>请输出一个 5 到 10 之间的数字:</h1>
<input id="num" type="text" />
<button type="button" οnclick="myFunction()">测试输入</button>
<p id="result"></p>

<script>
function myFunction()
{
	var res = document.getElementById("result");
	var data = document.getElementById("num").value;
	try
	{
		if(data == "")
			throw "不能为空,重新输入";
		if(isNaN(data))  //没有else if,只能用if
			throw "不是数字,重新输入";
		data = Number(data);
		if(data < 5)
			throw "错误:太小";
		if(data > 10)
			throw "错误:太大";
		else
			res.innerHTML = "正确";
	}
	catch(err)
	{
		res.innerHTML = err;
	}
}
</script>
</body>
</html>

output:

发布了137 篇原创文章 · 获赞 51 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/Pop_Rain/article/details/75050333