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