Understanding Try , Success and Failure in Scala

Try and Failure in scala are useful for handling exceptions. Let us start first with Try. Try indicates a computation that can result in either of the two namely, return a successfully computed value or result in an exception being thrown. The two sub classes that extend Try are Success and Failure. Hence if a method return a Try, you should understand that it will be either a Success or a Failure.


import scala.util.{Try,Success,Failure}

final case class Success[+T](value: T) extends Try[T] 
final case class Failure[+T](exception: Throwable) extends Try[T]

You can see that the Success has a constructor that takes a value of Type T ( This a generic type, can be anything). Similarly , Failure has a constructor that takes an Exception as input.

Try, Success, Failure – Example

To illustrate the usage, consider a function toNumber that takes a string as input and returns an Int if the string is a valid integer and if not an exception.

import scala.util.{Try,Success,Failure}

def toNumber(v:String): Try[Int] = {
    Try {
      Integer.parseInt(v);
    }
  }
 println(toNumber("h"));
 println(toNumber("1"));
 println(toNumber("0"));

Output

Failure(java.lang.NumberFormatException: For input string: "h")
Success(1)
Success(0)

This function return a Failure for the first input and returns valid integers for the next two cases. Let us see how we can handle a try and process it elegantly at the caller side.

Handling a function returning Try

We can use the pattern matching feature of scala on case classes to elegantly process a method that returns Try. If you have observed, you already know, both Success and Failure are indeed case classes.

toNumber("0") match {
    case Success(v) => println("valid number");
    case Failure(exception) => println("invalid number "+exception
      .getMessage);
  }

References

https://www.scala-lang.org/api/current/scala/util/Try.html

Leave a Comment