实例解析js中try、catch、finally的执行规则

try:  语句测试代码块的错误,一般把可能会出错的代码放到这里

catch: 只有try里面的代码块发生错误时,才会执行这里的代码,参数err记录着try里面代码的错误信息

finally: 无论有无异常里面代码都会执行

 

 代码如下
1 try{
2  console.log(0);
3  }catch(err){
4  console.log(1);
5  console.log(hello);
6  }finally {
7  console.log(2);
8  }
9  //最后结果分别打印出 0 2
10  /*
11  try{
12  a.b.c();
13  }catch (e){
14  console.log(1);
15  console.log(hello);
16  }finally {
17  console.log(2);
18  }
19  */
20  //最后结果分别打印出 1 2 报错:hello is not defined
21  /*
22  try{
23  a.b.c();
24  }catch (e){
25  console.log(1);
26  try{
27   console.log(hello);
28  }catch (e){
29   console.log(3);
30  }
31  }finally {
32  console.log(2);
33  console.log(word);
34  }
35  */
36  //最后结果分别打印出 1 3 2 报错:word is not defined
37  /*
38  try{
39  a.b.c();
40  }catch (e){
41  console.log(1);
42  console.log(hello);
43  }finally {
44  console.log(2);
45  console.log(word);
46  }*/
47  //最后结果分别打印出 1 2 报错:word is not defined

 

总结:

try里面的代码报错的时候,catch里面的代码才会执行,finally里面的代码永远会执行

catch和finally里面,正常的代码会从上到下顺序执行

如果只是catch里面代码出错,则报catch里面的错误

如果catch和finally都出错则会报finally里面的错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值