How to Handle Errors in Scala

exception handling
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.

When an exception occurs, say an Arithmetic Exception then the current operation is aborted. Then the runtime system looks for an exception handler that can accept an Arithmetic Exception. Control resumes with the innermost handler. If no such handler exists, the program terminates.


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 exceptions that occurred in the try block. You can have any number of try-catch blocks in your program according to need.

For example:

try {
    val div = 5/0
} catch {
    case ex: ArithmeticException => println("Cannot divide a number by zero")

Here 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

var text = ""
try {
    text = openAndReadAFile(filename)
} catch {
    case e: FileNotFoundException => println("Couldn't find that file.")

Here we are trying to read a file and if the file is missing then FileNotFoundException is matched. Then it will return “Couldn’t find that file.” as Output.


The Option in Scala is referred to as a carrier of single or no element for a stated type. When a method returns a value that 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 the 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 the 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 indicates 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.

package Playground

object handler extends App {

  val name = Map("abc" -> "author", "pqr" -> "coder")
  val x = name.get("abc")
  val y = name.get("xyz")

  println(x) //Some(author)
  println(y) //None
Handling error

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


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

The Either has two children which are named 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 that occurred inside the child Left of the Either and Right is utilized for Success.

package Playground

object handler extends App {

  def Name(name: String): Either[String, String] = {

    if (name.isEmpty) Left("No Data Found")
    else Right(name)


Handling error

As you can see when I pass an argument “Pallav” the output is “Right(Pallav)“.
And when I didn’t provide an argument the output is “Left(No Data Found)“.


Thank you guys for making it to the end of the blog I hope you gained some knowledge about How to handle errors in Scala.


For more detailed information you can use this link:

Written by 

Pallav is working as Software Consultant at Knoldus Inc. He is a technology enthusiast and a keen learner with more than 2 years of experience. He works as a Quality Catalyst in the organization. He has a good understanding of programming languages like Java and Scala. He likes to listen to songs and playing table tennis.

1 thought on “How to Handle Errors in Scala4 min read

Comments are closed.