try、catch、finally 用法总结:
1、不论有没有异样,finally 中的代码都会执行
2、当 try、catch 中有 return 时,finally 中的代码仍然会继续执行
3、try 或 catch 外面有 return 语句,finally 外面的表达式依旧会执行,但不影响 try.catch return 的值。
finally 语句执行不会影响 try 或 catch 的 return
const test = () => {
let a = 123;
try {console.log('this is - try - , a =', a);
return a;
} catch (error) {console.log('this is - catch - , a =', a);
return a;
} finally {console.log('this is - finally -, a =', a);
a = '000';
console.log('this is end of - finally -, a =', a);
}
};
console.log(test());
打印后果
// this is - try - , a = 123
// this is - finally -, a = 123
// this is end of - finally -, a = 000
// 123
异样 catch
const test = () => {
let a = 123;
try {console.log('this is - try - , a =', a);
throw new Error('test error');
return a;
} catch (error) {
a = 9999;
console.log('this is - catch - , a =', a);
return a;
} finally {
a = '000';
console.log('this is - finally -, a =', a);
}
};
console.log(test());
打印后果
// this is - try - , a = 123
// this is - catch - , a = 9999
// this is - finally -, a = 000
// 9999
这里要留神返回的不是援用类型。援用类型,finally 的批改会影响函数返回值
4、finally 代码中最好不要蕴含 return,会笼罩 try 和 catch 的 return
const test = () => {
let a = 123;
try {console.log('this is - try - , a =', a);
throw new Error('test error');
return a;
} catch (error) {console.log('this is - catch - , a =', a);
a = 9999;
return a;
} finally {console.log('this is - finally -, a =', a);
a = '000';
console.log('this is end of - finally -, a =', a);
return a;
}
};
console.log(test());
打印后果
// this is - try - , a = 123
// this is - catch - , a = 123
// this is - finally -, a = 9999
// this is end of - finally -, a = 000
// 000