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
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.")
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:
Error Information:
Use Cases:
Use Either when:
Type Parameters: