Last Updated: February 25, 2016
· brianhsu

Scala 2.10's scala.util.Try error handling.

Scala 2.10 has introduce a new method to do exception handling -- The scala.util.Try.

The class works very similar to Either[A, B] class. But with a better semantic.

You could wrap any code that might throw exceptions inside the Try.apply() function.

val result = Try(Integer.parseInt(...))

Now, the result will be one of the two subclass of Try -- Success or Failure.

If Integer.parseInt does not throw any exception, it will be a Success, otherwise it will be a Failure.

There are few ways to deal with the Try's result.

// Traditional Java way to check result
val myInt = if (result.isSuccess) { result.get } else { 0 }

// Or using getOrElse()
val myInt = result.getOrElse(0)

// Or handle exception ourself
val myInt: Try[Int] = result.recover {
    case e: Exception => 0

// Since scala.util.Try is a monad, we could use for-comprehension
for (myInt <- result) {
    println(myInt) // Only execute if result is a Success

// And of course map() / foreach() will works fine.
result.map(_ + 1).foreach(println)
Say Thanks

1 Response
Add your response


Thanks for the write up and the examples!

over 1 year ago ·