Library contents

Scala NonFatal

A malformed ticket count is a recoverable parsing problem. Handle it at the input boundary.

A simple example

NonFatal

  1. Start with Input "x" in a numeric field
  2. Do this Catch a conversion failure
  3. Result The caller can handle the bad input
A narrow handler allows a recoverable input error to take a different path from a serious runtime failure.

Syntax

Scala syntax
case scala.util.control.NonFatal(problem) =>
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Distinguish a malformed ticket count from a runtime failure

A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.

ResultNumberFormatException
Lesson.scala

object Lesson {
    def main(args: Array[String]): Unit = {
        try {
            "sold out".toInt
        } catch {
            case scala.util.control.NonFatal(problem) => println(problem.getClass.getSimpleName)
        }
    }
}
Output
NumberFormatException

Parsing the words sold out fails. The handler prints the actual exception class so the input problem is recognizable.

Advertisements

Read a donation total

The library has a signed-off box count written as decimal digits. Parse the entire quantity as a base-ten integer. Let the clerk correct a rejected record.

Given24
Worked resultQuantity accepted

Catch a unit in the count field

An equipment form expects an integer but the donor types the unit as well. Parse the entire quantity as a base-ten integer. Let the clerk correct a rejected record.

Given4kg
Worked resultReview quantity

What to watch for

Prefer catching NumberFormatException when only malformed numbers are expected. JVM errors such as OutOfMemoryError require a different recovery policy.

Documentation for NonFatal