In Scala, is there a pre-existing library function for converting exceptions to Options?

前端 未结 5 1394
心在旅途
心在旅途 2021-02-05 06:32

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:

5条回答
  •  孤城傲影
    2021-02-05 07:06

    Use 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)
    

提交回复
热议问题