使用finally语句

Gab*_*mas 24 javascript node.js

这是一个非常基本的问题.在Java中,我使用finally语句来关闭资源,因为"这是一个很好的做法".我在Javascript中开发,然后在Node.js中开发了几年,我从未使用过该finally语句.我知道在Node.js中我们所有人都遵循第一个参数错误处理模式.无论如何,以下2个片段也是如此:

try{
    throw 123
}catch (e){

}finally{
    console.log(1)
}
Run Code Online (Sandbox Code Playgroud)

.

try{
    throw 123
}catch (e){

}

console.log(1)
Run Code Online (Sandbox Code Playgroud)

两者都打印1.

为什么finally它有没有真正的好处关键字?清理代码可以放在catch中.

Mor*_*aie 21

最后,它不仅仅用于异常处理 - 它允许程序员避免因返回,继续或中断而意外绕过清理代码.

只是一个简单明了的例子来说明差异.有一个return打破了函数完成,但console.log在跳过finally最后一个时调用了in console.log.

let letsTry = () => {

  try {
    // there is a SyntaxError
    eval('alert("Hello world)');
    
  } catch(error) {
    console.error(error);
	
    // break the function completion
    return;
  } finally {
      console.log('finally')
  }

  // This line will never get executed
  console.log('after try catch')
}

letsTry();
Run Code Online (Sandbox Code Playgroud)


Lam*_*amp 11

但是尝试一下:

try {
    throw "foo"
} catch (e) {
    throw "bar"
} finally {
    console.log("baz")
}

console.log("quux")
Run Code Online (Sandbox Code Playgroud)

如果从该catch块内引发第二个错误,则该块后的代码try...catch将无法运行。即使
finally块中有错误,该catch块也将始终运行。

此外,finally即使a returnbreak语句停止了tryor catch块中的代码,该块也会运行。return语句中的finally块重写return在语句trycatch块。

function foo() {
    try {
        return "bar";
    } finally {
        return "baz";
    }
}

foo() // "baz"
Run Code Online (Sandbox Code Playgroud)


Sur*_*tta 3

finally 块有特殊用途。

\n\n
\n

finally 不仅仅适用于异常处理 \xe2\x80\x94 它允许程序员避免清理代码意外地被返回、继续或中断绕过。将清理代码放在finally 块中始终是一个好习惯,即使在预计不会出现异常的情况下也是如此。

\n
\n\n

因为它不会影响你的业务逻辑,但它仍然是编译器友好的,在内存方面。

\n