【问题标题】:Difference between code in JavaScript finally block and after try ... catch [duplicate]JavaScript 中的代码 finally 块和 try ... catch 之间的区别 [重复]
【发布时间】:2021-09-09 19:25:56
【问题描述】:

此问题可能与已回答的其他问题相似,但我找不到与 JavaScript 相关的答案。

finally 块中的代码与整个 try ... catch ... finally 语句之后的代码有什么区别?

也就是这段代码有什么区别:

try {
  f(x);
}
catch(e) {
  g(e);
}
finally {
  h(y);
}

还有这段代码:

try {
  f(x);
}
catch(e) {
  g(e);
}
h(y);

【问题讨论】:

  • finally 仅在使用 return 或另一个 throw 时会有所不同。见the specthe docs
  • 你指的是@CertainPerformance给出的答案吗?
  • “你指的是@CertainPerformance 给出的答案吗?” — 我不确定你的意思……我的两个cmets 都提到了你的问题。
  • 抱歉——我的意思是问您是否与@CertainPerformance 在他的回答中提出的观点相同。

标签: javascript try-catch try-catch-finally try-finally


【解决方案1】:

一个区别是,如果在 finally 中返回一个值,它将覆盖从之前的 trycatch 块中返回的值:

function foo() {
  try {
    throw new Error('1');
  } catch(e) {
    return '2';
  } finally {
    return '3';
  }
}
console.log(foo());

从 finally will also 返回可防止 trycatch 中的 throws 向外渗透 - 相反,只有 finally 的正常返回完成值将是结果。

(function() {
  try {
    try {
      throw new Error('oops');
    } catch (ex) {
      console.error('inner', ex.message);
      throw ex;
    } finally {
      console.log('finally');
      return;
    }
  } catch (ex) {
    // not entered into
    console.error('outer', ex.message);
  }
})();

【讨论】:

  • 并且,根据@SebastianSimon 建议的重复问题,即使出现错误,finally 块中的任何 other 代码(不仅仅是return 语句)都将运行在catch 块中抛出或return
  • “也会导致 try 或 catch 中的 throws 向外渗透”——你的意思是说它会防止它们向外渗透吗?
【解决方案2】:

我承认这个问题一开始让我摸不着头脑。但是看看MDN reference for try...catch 包括关于“Returning from a finally-block”的这个突出部分。看来,如果您从finally 块中return,它将覆盖从前面的trycatch 块返回或抛出的任何内容。因此,虽然您的示例可能相同,但如果您将其更改为:

try {
  return f(x);
}
catch(e) {
  throw g(e);
}
finally {
  return h(y);
}

...它与此有根本的不同:​​


try {
  return f(x);
}
catch(e) {
  throw g(e);
}
return h(y);

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2015-09-05
    相关资源
    最近更新 更多