finally

A Scala method to run any block of code slowly alvin March 10, 2018 - 12:56pm

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)

Scala exception handling (try/catch/finally and more)

Scala FAQ: How do I handle exceptions in Scala?

Solution: Basic exception handling in Scala is handled with its try/catch/finally syntax. (See the end of this article for links to tutorials on advanced exception handling in Scala.)

Here’s an example of Scala’s try/catch/finally syntax:

Scala: How to declare a variable (var) before using it in try/catch/finally

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.”

Problem

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.

A Java JDBC exception example showing try, catch, and finally

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: