关于javascript:trycatchfinally使用注意事项

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理