这是一个非常基本的问题。在 Java 中,我使用 finally 语句来关闭资源,因为“这是一个好习惯”。几年来,我一直在使用 Javascript 和 Node.js 进行开发,并且我从未使用过 finally
语句。我知道在 Node.js 中,我们所有人都遵循 first parameter error handling 模式。不管怎样,下面的 2 个片段都是一样的:
try{
throw 123
}catch (e){
}finally{
console.log(1)
}
.
try{
throw 123
}catch (e){
}
console.log(1)
都打印 1。
如果 finally
没有真正的好处,为什么它是关键字?清理代码可以放在catch里面。
最佳答案
finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
只是一个简单明了的例子来说明差异。有一个 return
会破坏函数完成,但是 finally
中的 console.log
会在最后一个 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();
关于javascript - finally 语句的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18251156/