Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.
If you ever need to intentionally throw and catch an exception with ScalaTest, here’s an example of how to do that:
If you happen to be using Dotty (Scala 3) and find that the
f string interpolator isn’t working, it’s a known bug. (It was implemented with a macro, and the old, experimental macro system has been dropped.) I’m writing this in January, 2019; I don’t know when it will work again. You can use the Java/Scala String.format method until it’s fixed:
val pi = scala.math.Pi println( "%1.5f".format(pi) )
I just read a short chapter in the book Effective Java, and realized I was doing something pretty dumb in my own code by always creating my own custom exceptions instead of using other exceptions already intended to be reused in the Java API.
At the time of this writing there aren’t many examples of the Scala
allCatch method to be found, so I thought I’d share some examples here.
In each example I first show the "success" case, and then show the "failure" case. Other than that, I won’t explain these, but hopefully seeing them in the REPL will be enough to get you pointed in the right direction:
Play Framework example: A controller action that handles a SQL exception, creates a new Form, and has custom error messages
If you need to handle a unique constraint in a database table field when writing an add or edit process in a Play Framework application, I hope this example will be helpful. In the end I’ll show:
Here’s a little example of how exceptions work with Scala Futures, specifically looking at the
onComplete ‘Failure’ case.
In this example I start three Futures that run for different lengths of time, and the shortest-running
Future throws an exception:
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 17.2, “How to add exception annotations to Scala methods so they can be called from Java.”
You want to let Java users know that a method can throw one or more exceptions so they can handle those exceptions with try/catch blocks.
@throws annotation to your Scala methods so Java consumers will know which methods can throw exceptions and what exceptions they throw.