Error Handling in Scala with Option, Try/Catch and Either

Reading Time: 3 minutes

Error handling is the process of handling the possibility of failure. For example, failing to read a file and then continuing to use that bad input would clearly be problematic. Noticing and explicitly managing these errors saves the rest of the program from various pitfalls.

Exceptions in Scala work the same way as in C++ or Java. When an exception occurs, say an Arithmetic Exception then the current operation is aborted, and the runtime system looks for an exception handler that can accept an Arithmetic Exception. Control resumes with the innermost such handler. If no such handler exists, the program terminates.

Try/Catch

Scala provides try and catch block for error handling. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in try block. You can have any number of try catch block in your program according to need.

Consider an example below

object Arithmetic {
   def main(args: Array[String]) {
      try {
         val z = 4/0
      } catch {
                  case ex: ArithmeticException => println("Cannot divide a number by zero")
              }
      }
}

Here in this example we are trying to divide a number by zero and catch the arithmetic exception in the catch block. The case ArithmeticException is matched and the statement “Cannot divide a number by zero” is printed.

Let’s take another example where we want to read a text file

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object fileRead {
  def main(args: Array[String])
    {	
	try {
		val t = new FileReader("input.txt")
	  }
	catch {
	  case x: FileNotFoundException => println("Exception: File missing")
        }
    }
}

Here in this example we are trying to read a file and if the file is missing then FileNotFoundException is matched and “File missing” is printed.

Option

The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is used i.e, the method defined returns an instance of an Option, in place of returning a single object or a null.

  • The instance of an Option that is returned here can be an instance of Some class or None class in Scala, where Some and None are the children of Option class.
  • When the value of a given key is obtained then Some class is generated.
  • When the value of a given key is not obtained then None class is generated.

Option type is used frequently in Scala programs and you can compare this with the null value available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value stored in the HashMap, or None if no value was found.


object option
{

	def main(args: Array[String])
	{
		val name = Map("abc" -> "author","pqr" -> "coder")

		
		val x = name.get("abc")
		val y = name.get("xyz")


		println(x)  //Some(author)
		println(y)  //None
	}
}

Here, key of the value “abc” is found so, Some is returned for it but key of the value “xyz” is not found so, None is returned for it.

Either

Either works just like Option with a difference being that with Either you can return a String that describes the problem that occurred.

The Either has two children which are named as Right and Left where, Right is similar to the Some class and Left is same as None class. Left is utilized for the failure where, we can return the error occurred inside the child Left of the Either and Right is utilized for Success.

// Scala program of Either

object EitherExample extends App
{

	def Name(name: String): Either[String, String] =
	{
	
		if (name.isEmpty)
	
			Left("No Name")

		else
			Right(name)
	}
	
	
	println(Name("Knoldus"))

	println(Name(""))
}

In this example the output of code will be “Right(Knoldus)” and “Left(There is no name.)”

1 thought on “Error Handling in Scala with Option, Try/Catch and Either3 min read

Comments are closed.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading