实例解析js中try、catch、finally的执行规则
try: 语句测试代码块的错误,一般把可能会出错的代码放到这里
catch:只有try里面的代码块发生错误时,才会执行这里的代码,参数err记录着try里面代码的错误信息
finally:无论有无异常里面代码都会执行
try{
console.log(0);
}catch(err){
console.log(1);
console.log(hello);
}finally{
console.log(2);
}
//最后结果分别打印出02
/*
try{
a.b.c();
}catch(e){
console.log(1);
console.log(hello);
}finally{
console.log(2);
}
*/
//最后结果分别打印出12报错:helloisnotdefined
/*
try{
a.b.c();
}catch(e){
console.log(1);
try{
console.log(hello);
}catch(e){
console.log(3);
}
}finally{
console.log(2);
console.log(word);
}
*/
//最后结果分别打印出132报错:wordisnotdefined
/*
try{
a.b.c();
}catch(e){
console.log(1);
console.log(hello);
}finally{
console.log(2);
console.log(word);
}*/
//最后结果分别打印出12报错:wordisnotdefined
总结:
try里面的代码报错的时候,catch里面的代码才会执行,finally里面的代码永远会执行
catch和finally里面,正常的代码会从上到下顺序执行
如果只是catch里面代码出错,则报catch里面的错误
如果catch和finally都出错则会报finally里面的错误
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下