Will it finally: 关于 try/catch 的一些细节

30次阅读

共计 1531 个字符,预计需要花费 4 分钟才能阅读完成。

随着 async /await 的出现,我最近发现自己在我的代码中使用了更多 try /catch /finally。但老实说,我终于用“finally”做了一点练习。当我去实际使用它时,我有点不确定它的细节。所以我把几个例子放在一起。
当你 throw 一个 catch
考虑你在一个 catch 块跑出一个异常。在退出函数之前没有什么可以捕获你的 throw。那“finally”会运行吗??
function example() {
try {
fail()
}
catch (e) {
console.log(“Will finally run?”)
throw e
}
finally {
console.log(“FINALLY RUNS!”)
}
console.log(“This shouldn’t be called eh?”)
}

example()
控制台结果

Will finally run?
FINALLY RUNS!
Uncaught ReferenceError: fail is not defined
at example (<anonymous>:3:5)
at <anonymous>:15:2

finally 运行,即使并没有打印最后一个日志语句!但它确实抛出了错误。
你可以看到 finally 有点特别; 它允许你在抛出错误和离开函数之间运行,即使抛出 catch 块。
尝试没有捕获 (catch)
您是否知道如果您提供 finally 块,您也不需要提供 catch 块?你可能做到了,但值得一提!
接下来的问题是:即使在 try 块中没有出错,finally 块也会被调用吗?

function example() {
try {
console.log(“Hakuna matata”)
}
finally {
console.log(“What a wonderful phrase!”)
}
}

example()
控制台结果
[log] Hakuna matata
[log] What a wonderful phrase!
是的,即使没有出错也会调用 finally。当然,当 does 出错时,它也会被调用。
这就是 finally 背后的想法 – 它可以让你处理这两种情况,正如你在这个例子中看到的那样:

function example() {
try {
console.log(“I shall try and fail”);
fail();
}
catch (e) {
console.log(“Then be caught”);
}
finally {
console.log(“And finally something?”);
}
}

example()
控制台结果
[log] I shall try and fail
[log]Then be caught
[log] And finally something?
那如果 return 了?finally 还会执行吗?
所以最后让你在异常发生时自己清理。但是什么时候什么都不会出错,你只是从函数中“返回”正常 … 在 try 块中?
看看下面的例子。example()中的 finally 块是否可以运行 after 你已经命中了 return 语句?
function example() {
try {
console.log(“I’m picking up my ball and going home.”)
return
}
finally {
console.log(‘Finally?’)
}
}

example()
控制台结果
[log] I’m picking up my ball and going home.
[log]Finally?
规则
try /catch /finally 上的 finally 块都将运行 – 即使你提前 catch 或 ’return`。
这就是它如此有用的原因; 无论发生什么情况,它都将运行,那么这就是将,始终要运行的代码的理想场所,比如容易出错的 IO 的清理代码。事实上,这就是本文的灵感来源。

正文完
 0