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)
I like looking at source code from other developers, I almost always learn something. In this case I knew that a
try expression in Scala returned a value, but I have never used it like this. This example is from the book, Learning Concurrent Programming in Scala.
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.
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.
Scala FAQ: Can you share some examples of the Scala try/catch/finally syntax? Also, can you show how to catch multiple exceptions, and just one exception with the Scala wildcard operator (_)?
The general Scala try/catch/finally syntax looks like this:
Java/JDBC try/catch/finally exception FAQ: Can you show me a decent example of how to catch a JDBC exception in a try/catch/finally block?
Beauty is in the eye of the beholder, but here's a JDBC example showing some Java code that uses a try/catch/finally block with a Java JDBC query: