try..catch 中的 finally 有什么意义?

vog*_*tix 5 javascript

是否有任何理由将代码放在finally块中而不是在try...catch语句后面放置代码。当然,在这两种情况下,代码都会运行

try {
   something();
} catch (error) {
   error_handling_with(error);
}
// code here gets executed whether in finally clause or not.
finally_something();
Run Code Online (Sandbox Code Playgroud)

finally以后有什么地方是必须的try...catch吗?我可以看到它在 Promise 中有用,但不是在这里。

Vig*_*aut 6

finally即使您提前返回try-catch或者即使您不处理try-catch. 这是我喜欢的一个例子:

function myFunction() {
  try {
    console.log('inside "try"');
    return
  } finally {
    console.log('inside "finally"');
  }

  console.log("after try-finally");
}

myFunction()
Run Code Online (Sandbox Code Playgroud)

当您运行时myFunction(),它将打印以下内容:

inside "try"
inside "finally"
Run Code Online (Sandbox Code Playgroud)

由于您从 返回try,因此它没有执行该try-finally块之后的任何指令。但是,Javascript 确实执行了该finally块。