Exception Handling in Scala Functional way

Exception Handling in Scala Functional way

Today let's deep dive in #scala specific functional programming exception handling, which is different from how exceptions are handled in OOP code,

Let's take an example, imagine we want to write a method that converts strings to integer values, and we also need a proper way to handle exception case when the method receives a string like "Hello" instead of "1", we would simply write following code to do the conversion.

def makeInt(s: String): Int =

try

??Integer.parseInt(s.trim)

catch

??case e: Exception => 0

if the conversion works, this method returns the correct Int value, but if it fails, the method returns 0, the method may have received "0" but it could receive any infinite number or other strings that will through an exception.

How do you know when the method really received a "0", or when it received something else? there's no way to know.

A common solution to this problem in #scala is to use Option[A] or Either[A,B]

Option[A] is a class with works with it's subclasses Some and None, using this classes we refactor the above code to handle exceptions more elegantly, here is the code and explanation.

def makeInt(s: String): Option[Int] =

?try

??Some(Integer.parseInt(s.trim))

?catch

??case e: Exception => None

  • you declare that def makeInt(s: String) returns an Option type.
  • If?makeInt?receives a string it?can?convert to an?Int, the answer is wrapped inside a?Some.
  • If?makeInt?receives a string it?can’t?convert, it returns a?None.

the above code can be read as, "When the given string converts to an integer, return the Int wrapped inside Some, such as Some(1). When the string can't be converted to an integer, an exception is thrown and caught, and method returns a None value.

Using a match expression

makeInt(x) match

case Some(i) => println(i)

case None => println("That didn’t work.")

  • In this example, if x can be converted to an Int, the expression on the right-hand side of the first?case?clause is evaluated; if?x?can’t be converted to an?Int, the expression on the right-hand side of the second?case?clause is evaluated.
  • After Option[A], let's now dive into Either[A,B] and understand how it is different from Option[A], and provides alternative to model and error which is otherwise is represented as None in Option[A].
  • The Either[A,B] type represents a wrapper that can contain either a value of type A or type B, and instance of it can be either Left[A] or Right[B]. the Left[A] projection is use to model an error, whereas we use Right[B] to hold the value produced after successful computation.

example of Either[A,B]

def findUserByIdEither(id: Int): Either[String, String] = {

val users = Map(1 -> "John", 2 -> "Jane")

users.get(id) match {

case Some(user) => Right(user)

case None => Left(s"User with id $id not found") } }

in the above program, Either[A,B] is used to handle exception when match case will try to find the User by it's Id, on success the Right projection is executed and gives the user name and if none of the id matches it throws an exception with proper message instead of just representing it with "None", that is the beauty of Either[A,B] we can model exceptions occurring to proper message.

key differences between Option[A] and Either[A,B]

Purpose:

  • Option represents presence/absence of a value (Some/None)
  • Either represents one of two possible types (Left/Right), typically success/failure

Error Information:

  • Option can't tell you why something failed (just None)
  • Either can include error details in the Left value

Use Cases:

  • Use Option when: You only need to know if a value exists
  • The failure reason is obvious or unimportant
  • Working with collections (Map.get returns Option)

Use Either when:

  • You need to know why something failed
  • You need to handle multiple error cases
  • You want to carry error context

Type Parameters:

  • Option[A] has one type parameter
  • Either[A, B] has two type parameters (Left and Right types)











要查看或添加评论,请登录

Kaustubh Chavan的更多文章

社区洞察

其他会员也浏览了