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.

Scala Exception/allCatch examples

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(Try("42".toInt))
val res2: scala.util.Try[Int] = Success(42)
                                                                                                                      
scala> allCatch.toTry(Try("hi mom".toInt))
val res3: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "hi mom")


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

Update

As a brief update, and for my own reference, here are examples of how to write methods/functions using allCatch in Scala with the Option, Try, and Either classes:

import scala.util.control.Exception._
import scala.util.{Try, Success, Failure}

// Option
def toInt(s: String): Option[Int] = allCatch.opt(Integer.parseInt(s))

// Try
def toInt(s: String): Try[Int] = allCatch.withTry(Integer.parseInt(s))

// Either
def toInt(s: String): Either[Throwable, Int] = 
    allCatch.either(Integer.parseInt(s))

See these Scaladoc pages for more information: