1

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

肥皂泡
382 声望6 粉丝

码农