初步理解js的嵌套try...catch...机制

js的嵌套try…catch…

由于初次接触js嵌套的try…catch…机制,被困惑了很久,还是自己动手实践才理解的更清楚,以下三种情况是我用来分析的三种情况:

1.内层catch没有将error返回或者throw出去

try{
  try {
    throw "myException"; // generates an exception
  }
  catch (e) {
    console.error('internal:'+ e);
  }
  console.log('demi');
}catch(error){
  console.error('external:'+ error);
}

output:

internal:myException
“demi”

由结果看来,首先try里面出现异常或者主动抛出异常,与它配套的catch是肯定可以捕获到的。但是内层catch若不把error返回或者throw出去,外层catch是捕获不到的,所以,外面的程序并不会终止,依然会继续往下跑。

2.内层catch将error返回出去

try{
  try {
    throw "myException"; // generates an exception
  }
  catch (e) {
    console.error('internal:'+ e);
    return e;
  }
  console.log('demi');
}catch(error){
  console.error('external:'+ error);
}

output:

internal:myException

由结果看来,内层catch若把error返回出去,是会被外层catch捕获到的,所以,外面的程序会终止,不会继续往下跑, 只是在这里return error了,所以外面catch的console.error()信息并不会打印。

3.内层catch将error throw 出去

try{
  try {
    throw "myException"; // generates an exception
  }
  catch (e) {
    console.error('internal:'+ e);
    throw new Error(e);
  }
  console.log('demi');
}catch(error){
  console.error('external:'+ error);
}

output:

internal:myException
external:Error: myException

由结果看来,内层catch若把error throw出去,也是会被外层catch捕获到的,所以,外面的程序仍旧会终止,不会继续往下跑。而且内层catch和外面的catch都会打印相对应的error信息。

所以,三种情况根据场景实际去应用啦!
这是js小白的初步见解,有错误的地方希望大家帮忙指正哦!

11.04日补充:
假如一个方法里面包含try…catch…这种类型,如果要中断程序就必须显示的抛出异常了,否则 return e 也只是返回了一个值,并没有中断外面的程序。看下面两个代码实践的输出:

1.直接return e, 不会中断外面程序


function test(){ 
    try {
    throw "myException"; // generates an exception
  	}
  	catch (e) {
    	console.error('internal:'+ e);
    	return e;
  	}
  }

try{
  test();
  console.log('demi');
}catch(error){
  console.error('external:'+ error);
}

output:

internal:myException
“demi”

2.throw e 中断外面程序

unction test(){ 
    try {
    throw "myException"; // generates an exception
  	}
  	catch (e) {
    	console.error('internal:'+ e);
    	throw new Error(e);
  	}
  }

try{
  test();
  console.log('demi');
}catch(error){
  console.error('external:'+ error);
}

output:

internal:myException
external:Error: myException

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值