try catch 错误处理;
执行规则:首先执行try中的代码 如果抛出异常会由catch去捕获并执行 如果没有发生异常 catch去捕获会被忽略掉 但是不管有没有异常最后都会执行。
try 语句使你能够测试代码块中的错误。
catch 语句允许你处理错误。
throw 语句允许你创建自定义错误。(抛出错误)
finally 使你能够执行代码,在 try 和 catch 之后,无论结果如何。
const a = null
try {
const b = JSON.parse(a)
console.log(a.name)
} catch (e) {
console.log("发生异常:" + e)
}
上面是系统抛出的异常,也可以自定义抛出异常:
const a = null
try {
if (a == null || a == '') {
throw '值为空'
} else {
console.log(a)
}
} catch (e) {
console.log("发生异常:" + e)
}
最后
<p>请输出一个 5 到 10 之间的数字:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">测试输入</button>
<p id="mess"></p>
<script type="text/javascript">
function myFunction(){
try{
var x=document.getElementById("demo").value; // 取元素的值
if(x=="") throw "值为空"; //根据获取的值,抛出错误
if(isNaN(x)) throw "不是数字";
if(x>10) throw "太大";
if(x<5) throw "太小";
}
catch(err){
var y=document.getElementById("mess"); //抓住上面throw抛出的错误,给p标签显示
y.innerHTML="错误:" + err + "。";
} finally {
document.getElementById("demo").value = "";
}
}
网友评论