Back2Basics: Exception Handling – #2

monads

In our previous blog, we have seen how we can handle exceptions using try/catch and Try block.  In this blog, we will explore how we can handle exceptions using Either.

Either, just like a Try, is also a container type which can have one value either Left or Right at a time. We can also use Option to handle exceptions but if an exception occurs returning None, it will not give enough information about the reason for the failure. Either has two parts i.e Left and Right. Left and Right are case classes which inherit from Either. Left part contains the exceptions and Right contains the success value.

Let’s take an example,

Notice the return type of divide method is Either[String, Int]. Left part contains the error message and Right part contains the success value.

Let’s try with the positive and negative value of denominator,

 So, it is working fine. Now how to decide whether Either has left or right result.  Either provides two methods isLeft and isRight to check which type of value Either holds.

How to get values from Either?

There are many ways we will talk about all one by one.  One way to get values is by doing left and right projection. We can not perform any operation i.e, map, filter etc; on Either, till Scala 2.11. Either provide left and right methods to get the left and right projection. Projection on either allows us to apply functions like map, filter etc.

For example,

When we applied right on either, it returned RightProjection. Now we can extract the value from right projection using get, but if there is no value the compiler will blow up using get. So, we can use getOrElse to make sure compiler does not blow up if there is no value.

We can get values after checking whether either has value in left or right.

Though we got the value from either but code is not elegant. We are first querying it whether it is left or right and then getting the value from it. Can we have the better way to do this? Yes, pattern matching is very powerful and elegant way to get the value. Let’s try it with pattern matching.

Can we make it more concise and expressive? Yes, we can give a try applying fold to it. Let’s see.

We have seen how we can handle exceptions using Either and how we can get values from Either. We will explore more about Either in future blogs. Till then stay tuned 🙂

Please feel free to suggest and comment.

References:

  1. Daily Scala: Either
  2. Try, Option or Either?

knoldus-advt-sticker


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.

5 thoughts on “Back2Basics: Exception Handling – #2

Leave a Reply

%d bloggers like this: