在 Scala 中,是否有用于将异常转换为选项的预先存在的库函数? [英] In Scala, is there a pre-existing library function for converting exceptions to Options?

查看:41
本文介绍了在 Scala 中,是否有用于将异常转换为选项的预先存在的库函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这基本上是为了包装 java 工厂方法,如果无法根据输入创建项目,则会抛出异常.我正在基础库中寻找类似的东西:

This is basically to wrap java factory methods which throw exceptions if the item can't be created based on the inputs. I'm looking for something in the base library like:

 def exceptionToOption[A](f: => A):Option[A] ={
    try{
      Some(f)}
    catch{
      case e:Exception => None}
  }

用法:

val id:Option[UUID] = exceptionToOption(UUID.fromString("this will produce None"))

我知道我可以自己写,但我想检查一下我没有重新发明轮子.

I know I can write my own but I want to check I am not re-inventing the wheel.

推荐答案

使用 scala.util.control.Exception:

import scala.util.control.Exception._

allCatch opt f

你可以让它更复杂.例如,只捕获算术异常并检索异常:

And you can make it more sophisticated. For example, to catch only arithmetic exceptions and retrieve the exception:

scala> catching(classOf[ArithmeticException]) either (2 / 0)
res5: Either[Throwable,Int] = Left(java.lang.ArithmeticException: / by zero)

这篇关于在 Scala 中,是否有用于将异常转换为选项的预先存在的库函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆