Why should one prefer Option for error handling over exceptions in Scala?

exception, functional-programming, scala

Solution

At this specific section, `Option` is used mostly as an example because the operation used (calculating the `mean`) is a partial function, it doesn't produce a value for all possible values (the collection could be empty, thus there's no way to calculate the mean) and `Option` could be a valid case here. If you can't calculate the `mean` because the collection is empty just return a `None`.

But there are many other ways to solve this problem, you could use `Either[L,R]`, with the `Left` being the error result and a `Right` as being the good result, you could still throw an exception and wrap it inside a `Try` object (which seems more common nowadays due to it's use in `Promise` and `Future` computations), you could use ScalaZ Validation if the error was actually a validation issue.

The main concept you should take a way from this part is that the error should be part of the return type of the function and not some magic operation (the exception) that can't be reasonably declared by the types.

And as a shameless plug, I did blog about Either and Try here.

Problem

So I'm learning functional Scala, and the book says exception breaks referential transparency, and thus `Option` should be used instead, like so: ``` def pattern(s: String): Option[Pattern] = { try { Some(Pattern.compile(s)) } catch { case e: PatternSyntaxException => None } } ``` This seems pretty bad; I mean it seems equivalent to: ``` catch(Exception e){ return null; } ``` Save for the fact that we can distinguish "null for error" from "null as genuine value". It seems it should at least return something that contains the error information like: ``` catch { case e: Exception => Fail(e) } ``` What am I missing?

Original source