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

栏目: JavaScript · 发布时间: 7年前

内容简介:随着async /await的出现,我最近发现自己在我的代码中使用了更多try /catch /finally。但老实说,我终于用“finally”做了一点练习。当我去实际使用它时,我有点不确定它的细节。所以我把几个例子放在一起。考虑你在一个catch块跑出一个异常。在退出函数之前没有什么可以捕获你的throw。那“ finally”会运行吗??控制台结果

随着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的清理代码。事实上,这就是本文的灵感来源。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Hackers

Hackers

Steven Levy / O'Reilly Media / 2010-5-30 / USD 21.99

This 25th anniversary edition of Steven Levy's classic book traces the exploits of the computer revolution's original hackers -- those brilliant and eccentric nerds from the late 1950s through the ear......一起来看看 《Hackers》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具