try 、catch 、finally 、throw 测试js错误

时间:2023-02-18 20:12:20

try语句允许我们定义在执行时进行错误测试的代码块。

catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块。

finally 语句在 try 和 catch 之后无论有无异常都会执行。

throw 语句创建自定义错误。

JavaScript 语句 try 和 catch 是成对出现的。

例子:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body> <p>请输出一个 5 到 10 之间的数字:</p> <input id="demo" type="text">
<button type="button" onclick="myFunction()">测试输入</button>
<p id="message"></p> <script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "值为空";
if(isNaN(x)) throw "不是数字";
x = Number(x);
if(x < 5) throw "太小";
if(x > 10) throw "太大";
}
catch(err) {
message.innerHTML = "错误: " + err;
}
}
</script> </body>
</html>