Scala 捕捉混乱
我最近看到过这样的代码:
val maybeInt = catching(classOf[NFE]) opt arg.toInt
What is this opt
?一个选择?为什么不使用 getOrElse 来提取值?在上面的代码中,如果抛出 NumberFormatException,maybeInt
会是 None 吗?
I've recently seen code like this:
val maybeInt = catching(classOf[NFE]) opt arg.toInt
What is this opt
? An Option? Why isn't it using getOrElse to extract the value? In the above code, will maybeInt
be None if a NumberFormatException gets thrown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
捕捉
看起来像是某种方法调用,不是吗?确实如此,但它实际上返回了类Catch
的实例;它不直接接受参数。此类有两个对于处理异常特别有用的方法(还有几个用于捕获多个异常)。第一个是这里使用的——你给它一些可能抛出异常的东西,如果一切顺利,它会返回
Some(result)
,如果一切顺利,它会返回None
捕获了目标异常:然后您可以使用
map
或filter
或getOrElse
或任何其他用于处理选项的内容来处理此异常。另一个有用的方法是
either
,如果抛出异常则返回Left(exception)
实例,如果抛出异常则返回Right(result)
事实并非如此:然后您可以使用
fold
或映射到一个选项或您喜欢用其中任何一个做的任何其他事情。请注意,您可以定义一个捕获器并多次使用它(因此您不需要每次解析整数时都创建捕获器对象):
编辑:正如丹尼尔在评论中指出的那样,这仍然会创建临时的
Catch[Option]
;给定方法签名,没有一种简单的方法可以让它捕获异常并生成选项而不创建任何额外的对象。这让我想起了为什么我要编写自己的方法来做到这一点:catching
looks like it's some sort of method call, doesn't it? It is, but it actually returns an instance of a classCatch
; it doesn't directly take an argument. This class has two methods that are particularly useful for dealing with exceptions (and several more for catching multiple exceptions). The first iswhich is being used here--you give it something that may throw an exception, and it will return
Some(result)
if everything went okay, andNone
if the targeted exception was caught:You can then deal with this with
map
orfilter
orgetOrElse
or whatever else you use to deal with options.The other useful method is
either
, which returns an instance ofLeft(exception)
if an exception was thrown, and aRight(result)
if it was not:You can then use
fold
or map to an option or whatever else you like doing with eithers.Note that you can define a single catcher and use it multiple times (so you don't need to create the catcher object every time you, for example, parse an integer):
Edit: as Daniel points out in the comments, this still creates a temporary
Catch[Option]
; given the method signatures, there isn't an easy way to just have it trap exceptions and generate options without creating any extra objects. This reminds me why I write my own methods to do exactly that:当只有一个问题时,我使用一种更简单的模式:
我绝对还不是 Scala 专业人士,我想你可以找到更短的东西
I use a more simple pattern when there is only one catch :
I'm definitely not yet a Scala pro, and I guess you could find shorter stuff