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} }
Usage:
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.
try/catch/finally A basic way we can handle exceptions in Scala is the try/catch/finally construct, really similar to the Java one. In the following example, to make testing easier, we'll return a different negative error code for each exception caught: def tryCatch(a: Int, b: Int): Int = { try { return Calculator.
The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util. Either type. Instances of Try[T] , are either an instance of scala.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With