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
- Start with An attempt to parse "x" as an integer
- Do this Recover with 0
- Result Success containing 0
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.
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)
}
}
}
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
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.
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.