Tutorials Hut

Tutorials Hut

Scala Exceptions, Try Catch, Options, Success and Failure

In most programming languages there are exceptions and errors and features to handle them, Scala exceptions can be handled by using try, catch, options (some and none), Success and Failure. In this article we will look into details of each of these.

Scala Exceptions and Use of try and catch Block

In Scala code if an exception occurs we can use a try catch block like Java to handle it. The code which may throw some side effects or exceptions goes inside try block and in catch block we catch any error and handle as per business need.

Example:

object ScalaExceptions {

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

	try {

  	Integer.parseInt("q")

	} catch {

  	case e: Exception => println("Some exception while parsing, do something, exception message: "+e.getMessage)

	}
  }
}

Output

Some exception while parsing, do something, exception message: For input string: “q”

Scala Try Catch With Finally

Similar to Java, Scala also has a finally block, so if we want to execute a block of code if there is an exception or not in all cases then we can add one finally block with try and catch.

Example:

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

  	try {

    	Integer.parseInt("q")

  	} catch {

    	case e: Exception => println("Some exception while parsing, do something, exception message: "+e.getMessage)

  	} finally  {

    	println("In finally, we can close some resources, do some imp work.")

  	}
	}
  }

Output

Some exception while parsing, do something, exception message: For input string: "q"
In finally, we can close some resources, do some imp work.

Options (Some and None) In Scala and Use

Scala has a way to wrap result and send by using options, for example if your method is supposed to return sometimes valid result and sometimes null/error in that case Scala recommends to use options and when there is value, you can use and return Some of value or None. Note that Options, Some and None all are reserved keywords. See the below example how we will write a method and return some when we have valid value else None.

Example Of Options in Exception:

object ScalaExceptions {

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

	println("Parse XYZ to Int and result: "+parseStringToInt("xyz"))

	println("Parse 100 to Int and result: "+parseStringToInt("100"))

  }

 def parseStringToInt(input: String): Option[Int] = {

  try {

	Some(Integer.parseInt(input))

  } catch {

	case e: Exception => None
  }
 }
} 

Output

Parse XYZ to Int and result: None
Parse 100 to Int and result: Some(100)

Try, Success and Failure in Scala

Try is a reserved keyword in Scala which is used for exception handling, if we have some code which can throw an exception in that case we can use this to return results.Try will return Success of some value or Failure and the caller needs to handle these two results and take some action.

Let’s see how we can handle parsing string to int using Try, Success and Failure.

Example:

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

object ScalaExceptions {

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

	println("Parse XYZ to Int and result: "+parseStringToIntUsingTry("xyz"))

	println("Parse 100 to Int and result: "+parseStringToIntUsingTry("100"))
  }
  def parseStringToIntUsingTry(input: String): Try[Int] = {

	try {
      Success(Integer.parseInt(input))
	} catch {
  	case e: Exception => Failure(e)
	}
  }

}

Output

Parse XYZ to Int and result: Failure(java.lang.NumberFormatException: For input string: "xyz")
Parse 100 to Int and result: Success(100)

References

Next Article

  • Scala Collection

















  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    Scroll to Top