By Alvin Alexander. Last updated: March 7, 2020
At the time of this writing there aren’t many examples of the Scala Exception
object allCatch
method to be found, so I thought I’d share some examples here.
In each example I first show the “success” case, and then show the “failure” case. Other than that, I won’t explain these examples too much, but hopefully seeing them in the REPL will be enough to get you pointed in the right direction:
scala> import scala.util.control.Exception._ import scala.util.control.Exception._ // OPTION scala> allCatch.opt("42".toInt) res0: Option[Int] = Some(42) scala> allCatch.opt("42a".toInt) res1: Option[Int] = None // TRY scala> allCatch.toTry("42".toInt) res2: Any = 42 scala> allCatch.toTry("42a".toInt) res3: Any = Failure(java.lang.NumberFormatException: For input string: "42a") // EITHER scala> allCatch.either("42".toInt) res4: scala.util.Either[Throwable,Int] = Right(42) scala> allCatch.either("42a".toInt) res5: scala.util.Either[Throwable,Int] = Left(java.lang.NumberFormatException: For input string: "42a")
It’s nice that allCatch
supports Option
, Try
, and Either
; that’s cool, and convenient.
While I’m in the allCatch
neighborhood, here’s how you can write a string-to-int conversion function with allCatch
:
import scala.util.control.Exception._ def makeInt(s: String): Option[Int] = allCatch.opt(s.toInt)
See these Scaladoc pages for more information: