Library contents

Scala Try and recover

Try captures a nonfatal exception as a Failure or wraps the result in Success. recover can supply a fallback for a selected exception type.

A simple example

Try and recover

  1. Start with An attempt to parse "x" as an integer
  2. Do this Recover with 0
  3. Result Success containing 0
The failed conversion enters the recovery branch, which supplies the fallback.

Syntax

Scala syntax
Try(expression).recover { case e: SpecificException => fallback }
Run this example in Scala

Save the program as Lesson.scala. Use Scala 2.13.

scalac Lesson.scala
scala Lesson

Handle an invalid divisor without losing the batch

A batch processor must distinguish an anticipated input problem from a different failure. Examine the operation's error information before deciding whether to skip one record, report the cause or stop.

First output lineSuccess(4)
Lesson.scala
import scala.util.Try

object Lesson {
  def main(args: Array[String]): Unit = {
    for (divisor <- List(2, 0)) {
      val result = Try(8 / divisor).recover { case _: ArithmeticException => 0 }
      println(result)
    }
  }
}
Output
Success(4)
Success(0)

The recovery below handles division by zero only. Keeping the result inside Try leaves an unexpected failure distinguishable from a successfully recovered value.

Scala documentation for Try and recover

Advertisements

Split a studio hire fee

Two groups register for a 24-credit rehearsal. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.

Given24 credits / 2 groups
Worked resultShare calculated

Hold an empty field-trip batch

A trip has a 30-credit fixed fee and no groups registered yet. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.

Given30 credits / 0 groups
Worked resultHold batch