Recover in Scala

import scala.util.Try

// This function throws an exception
def mayThrow(): Unit = {
  throw new RuntimeException("a problem")
}

def main(args: Array[String]): Unit = {
  // In Scala, we use Try to handle exceptions
  val result = Try {
    mayThrow()
    println("After mayThrow()")
  }.recover {
    case e: Throwable => println(s"Recovered. Error:\n ${e.getMessage}")
  }

  // The result is a Success if no exception was thrown, or a Failure if an exception occurred
  result.foreach(_ => println("This won't be printed if an exception occurred"))
}

In Scala, we don’t have a direct equivalent to Go’s panic and recover mechanism. Instead, we use Scala’s exception handling and the Try monad to achieve similar functionality.

The mayThrow function simulates a function that might throw an exception (equivalent to Go’s panic).

In the main function, we use Try to wrap the potentially throwing code. The recover method on Try is similar to Go’s recover in that it allows us to handle any exceptions that were thrown.

If an exception occurs, the code inside recover will be executed, printing the error message. If no exception occurs, the code after mayThrow() inside the Try block will be executed.

The result.foreach at the end demonstrates that any code after a caught exception will still be executed, unlike in the Go example where execution stops at the point of panic.

To run this Scala program:

$ scala recover.scala
Recovered. Error:
 a problem

This example shows how Scala handles exceptions in a way that’s somewhat analogous to Go’s panic and recover mechanism, but with its own idiomatic approach using Try and pattern matching.