https://www.w3school.com.cn/js/js_errors.asp
- try 语句使您能够测试代码块中的错误。
- catch 语句允许您处理错误。
- throw 语句允许您创建自定义错误。
- finally 使您能够执行代码,在 try 和 catch 之后,无论结果如何。
try {
供测试的代码块;
if( 条件 ) throw "自定义返回的错误";
if( 条件 ) throw "自定义返回的错误";
} catch (err) {
处理错误的代码块;
} finally {
无论 try / catch 结果如何都执行的代码块
}
<!DOCTYPE html>
<html>
<body>
<p>请输入 5 到 10 之间的数字:</p>
<input id="demo" type="text" />
<button type="button" onclick="myFunction()">检测输入</button>
<p id="p01"></p>
<script>
function myFunction() {
var message = document.getElementById('p01');
var x = document.getElementById('demo').value;
message.innerHTML = '';
try {
if (x == '') throw '是空的';
if (isNaN(x)) throw '不是数字';
x = Number(x);
if (x > 10) throw '太大';
if (x < 5) throw '太小';
} catch (err) {
message.innerHTML = '输入:' + err.message;
} finally {
document.getElementById('demo').value = '';
}
}
</script>
</body>
</html>