Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 802
Noel Kennedy Avatar asked Nov 04 '11 17:11

Noel Kennedy


People also ask

How do you handle exceptions in Scala?

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.

What is try in Scala?

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.


1 Answers

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) 
like image 145
Daniel C. Sobral Avatar answered Oct 23 '22 04:10

Daniel C. Sobral