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?
Next, let’s take a look at how we can handle exceptions in Scala. Unlike Java, Scala offers multiple ways to do it, and we can choose a method that best fits our needs. The try/catch/finally keyword group is the most familiar way to handle exceptions. Simply put, we wrap the risky code in a try block and the error handling in a catch block.
In this article, we talked about Scala’s support for exception handling. When choosing between catch objects and Try/Success/Failure, the trade-off is between code accessibility and code reusability. In Scala, they are definitively preferable to try/catch/finally since they provide an easier way to achieve functional composability.
println ("IOException occurred.") println ("Arithmetic Exception occurred.") Arithmetic Exception occurred. In Scala a single catch block can handle all kinds of exceptions thus providing flexibility. If we want some part of our code to execute irrespective of how the expression terminates we can use a finally block.
We can make use of any number of Try-Catch Blocks in a program. Here’s how we would deal with the above situation: a. Another Example Let’s take another example of Scala Exception Handling:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With