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

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)

Yes, you can take a look to the scala.util.control.Exception object. Especially, the allCatch function.


As of scala 2.10, you can run your code (e.g. factory method) in a scala.util.Try and then convert it with toOption:

import scala.util.Try
Try("foo".toInt).toOption  // None
Try("7".toInt).toOption    // Some(7)

Or translated to your original example:

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