Error handling in Scala can just be written like Java. Put in a little bit of pattern matching magic and you are done. However, given a little use of Scala built-in terrific beauties it can be made much better. Let us have a look.
Let us look at a quick example
So we have a method called sayHello which misbehaves when you do not pass a string to it. If you call it without a string, it blows up and hence the letMeSayHello invocation blows up as well.
Ok, now traditionally we have been so used to try catch blocks that we put them around.
Ok, so far so good. So we can really write Java in Scala 😉
Now let us see a better way (Idiomatic way!) of handling this
Scala comes with something called a Try. The Try type represents a computation that may either result in an exception, or return a successfully computed value. It’s similar to, but semantically different from the scala.util.Either type. Instances of Try[T], are either an instance of scala.util.Success[T] or scala.util.Failure[T].
Interesting, let us see how our code changes now
So, we put a Try block around out sayHello method code. Now the method, letMeSayHello does not need to do explicit error handling. It gets back either Success(“Hello”) or Failure(java.lang.Exception: Huh!)
In the above scenario, it would get Failure(java.lang.Exception: Huh!) and you would be able to extract the value with
Now, there are various ways of dealing with this. You could pattern match on the boolean and take an action like
OR you could simply do a getOrElse
OR you could let the letMeSayHello method handle the success and failure
OR you could get even fancier ! I like this one. The awesome recover mechanism
The recover allows you to recover in case of failures with an alternate condition that you would want to execute which results in a success. Hence, in this case, we mentioned that either we would get a success by default or we would convert the error into a success scenario by writing a recover block so that we can confidently call letMeSayHello.get