If you ever need to intentionally throw and catch an exception with ScalaTest, here’s an example of how to do that:
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:
The book, Advanced Scala with Cats, has a nice little function you can use to run a block of code “slowly”:
def slowly[A](body: => A) = try body finally Thread.sleep(100)
I’d never seen a try/finally block written like that (without a
catch clause), so it was something new for the brain.
In the book they run a
factorial method slowly, like this:
slowly(factorial(n - 1).map(_ * n))
FWIW, you can modify
slowly to pass in the length of time to sleep, like this:
def slowly[A](body: => A, sleepTime: Long) = try body finally Thread.sleep(sleepTime)
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.17, “How to declare a variable (var) before using it in try/catch/finally.”
You want to use an object in a
try block, and need to access it in the
finally portion of the block, such as when you need to call a
close method on an object.
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.16, “How to match one or more exceptions with try/catch in Scala.”
You want to catch one or more exceptions in a try/catch block.
The Scala try/catch/finally syntax is similar to Java, but it uses the
match expression approach in the
This post contains a collection of Scala control structures examples. I initially created most of these in the process of writing the Scala Cookbook. Unlike the Cookbook, I don’t describe them much here, I just show the examples, mostly as a reference for myself (and anyone else that can benefit from them).
if/then control structures:
Here are some examples of the Scala if/then control structure:
Sometimes when I write small Scala scripts and programs I loosen the reins and use a
var. When you do this and you may need to occasionally create a null variable (a var, not a val), such as when you need to declare a variable right before using it in a try, catch, finally block.