Some Scala Exception ‘allCatch’ examples

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._

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

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.

There may be better ways to use this method. If you know of any, feel free to leave a comment below.

See these Scaladoc pages for more information: