Back2Basics: Exception Handling – #3


In our previous blog Exception Handling – #2, we talked about how we can handle exception using Either.

In this blog, we will explore further about Either, how we can elegantly handle exceptions using Either while working with Collections. We use collections when we want to perform some operations on elements. But what if something goes wrong while performing the transformation, do you have any idea how to handle such situation?

Well, Scala’s Either helps us to handle such situations very elegantly.

Let us define a method that reads the file and calculates it’s content length.

We will now see how we can deal with a collection of data. Let’s say we have a collection of names of files whose content length we want to calculate. So, to do so we need to map each element of the list of file names and call readFilesFromListOfFiles function on it.

when we call readFilesFromListOfFiles function, our program will blow up as the third file does not exist. The output will be: invalid_file_name (No such file or directory)
at main.scala.models.A$A172$A$A172.readFile(
at main.scala.models.A$A172$A$A172.$anonfun$readFilesFromListOfFiles$1(
at main.scala.models.A$A172$A$A172.$anonfun$readFilesFromListOfFiles$1$adapted(
at main.scala.models.A$A172$A$A172.readFilesFromListOfFiles(
at #worksheet#.#worksheet#(

Scala’s Either provides us with facilities to tackle such situations very elegantly. We can refactor our readFile() function as follows:

Now, calling readFilesFromListOfFiles will give the result:

List[Either[String,Int]] = List(Right(28), Right(25), Left(invalid_file_name (No such file or directory)))

To make it more expressive, we can use fold function. From this statement => readFile(name), we are getting a list of either, we can use a fold function on this transformation, now, we can work with the left part and the right part separately, here when we are getting left part, we are printing error and with right part we are printing value. So transforming a list of file names to list of either and with the fold, we are getting a list of Strings.

Now the result will be:

File’s length: 28
File’s length: 25
Error: invalid_file_name (No such file or directory)

So, we have seen how we can handle exceptions if we are working with collections.

Feel free to suggest or comment.


The Neophyte’s Guide to Scala Part 7: The Either Type


Written by 

I am a Software Consultant and has experience of more than 1.5 years. I like to study and write about latest technologies.

1 thought on “Back2Basics: Exception Handling – #3

Leave a Reply

%d bloggers like this: