Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Back2Basics: Exception Handling (Part 3)

DZone's Guide to

Back2Basics: Exception Handling (Part 3)

Having trouble handling exceptions? Let's take a look at how to tackle exceptions using Either and working with Collections.

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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

In this blog, we will further explore Either and 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 a situation?

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

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

def readFilesFromListOfFiles(list: List[String]) = {
  list.map(name => readFile(name))
}

def readFile(filename: String) = {
  Source.fromFile(filename).getLines.mkString.length
}


Now, we will 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 this, we need to map each element of the list of file names and call the readFilesFromListOfFiles function.

val listOfFiles = List("file1", "file2", "invalid_file_name")


When we call the  readFilesFromListOfFiles  function, our program will blow up as the third file does not exist. The output will be:

java.io.FileNotFoundException: invalid_file_name (No such file or directory)
at java.io.FileInputStream.open0(eitherHandlingCollections.sc)
at java.io.FileInputStream.open(eitherHandlingCollections.sc:191)
at java.io.FileInputStream.(eitherHandlingCollections.sc:134)
at scala.io.Source$.fromFile(eitherHandlingCollections.sc:87)
at scala.io.Source$.fromFile(eitherHandlingCollections.sc:72)
at scala.io.Source$.fromFile(eitherHandlingCollections.sc:50)
at main.scala.models.A$A172$A$A172.readFile(eitherHandlingCollections.sc:9)
at main.scala.models.A$A172$A$A172.$anonfun$readFilesFromListOfFiles$1(eitherHandlingCollections.sc:5)
at main.scala.models.A$A172$A$A172.$anonfun$readFilesFromListOfFiles$1$adapted(eitherHandlingCollections.sc:5)
at scala.collection.immutable.List.map(eitherHandlingCollections.sc:272)
at main.scala.models.A$A172$A$A172.readFilesFromListOfFiles(eitherHandlingCollections.sc:5)
at #worksheet#.#worksheet#(eitherHandlingCollections.sc:12)


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

def readFile(filename: String): Either[String, Int] = {
  try {
    Right(Source.fromFile(filename).getLines.mkString.length)
  }
  catch {
    case ex: Exception => Left(ex.getMessage)
  }
}


Now, calling the readFilesFromListOfFiles   will give users the following 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 the fold   function. From the statement  list.map(name => readFile(name) , we are getting a list of either. We can use a fold function on this transformation. Therefore, we can work with the left part and the right part separately when we are getting the left part. We are printing the error, and with right part, we are printing the value. So, transforming a list of file names to a list of either and with the fold, we are getting a list of  Strings.

def readFilesFromListOfFiles(list: List[String]) = {

 list.map (name => readFile (name))
 .map (_.fold (err => s"Error: $err", value => s"\nFile's length: $value"))
 .foreach (println (_) )
}


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.

References:

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

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:
java ,tutorial ,exception handling ,scala ,either

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}