Scala Try

The Try type in scala represents a computation that may either result in an exception, or return a successfully computed value.

In this post, We see how we can use Try type with an example.

Assume that we have a list of string and want to convert each value into number and If the value is not valid, then we have to throw an exception. We also do not want to break the program when an exception has been thrown.

Refer the below example to know how we can do that with Try type.



import scala.util.{Failure, Try}

object ScalaTryCatchExample {

    def main(args: Array[String]): Unit = {

        val values = List("1", "2", "3", "test", "5")

        values.foreach(value => {

            val tryOption = Try(convertValuesAsNumber(value))
            tryOption match {
                case Failure(e) =>
                    println(s" $value is not valid number. Exception is $e")
                case _ =>
            }
            println("Number:" + tryOption.toOption)
        }
        )

    }

    def convertValuesAsNumber(value: String): Integer = {
        if (value == null || !value.matches("[0-9]")) {
            throw new IllegalArgumentException()
        }
        Integer.valueOf(value)
    }
}


In the above Scala Object, we have “convertValuesAsNumber” method which is used to convert a string value into a number and also it throws an exception when if the value is null and not a valid number.

Here we wrap the convertValuesAsNumber method call into Try type. So when an exception throws, it would not break the program immediately. Instead the failure object is returned. So we can use match to find out this and finally call toOption method to get the value. If any exception throws then it will return a ‘None’ option.

We can also re-write the above program like below,


import scala.util.{Failure, Try}

object ScalaTryCatchExample {

    def main(args: Array[String]): Unit = {

        val values = List("1", "2", "3", "test", "5")

        values.foreach(value => {

            val tryOption = Try(Integer.valueOf(value))
            tryOption match {
                case Failure(e) =>
                    println(s" $value is not valid number. Exception is $e")
                case _ =>
            }
            println("Number:" + tryOption.toOption)
        }
        )

    }
}


The output of the above example is given below


Number:Some(1)
Number:Some(2)
Number:Some(3)
 test is not valid number. Exception is java.lang.IllegalArgumentException
Number:None
Number:Some(5)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s