TExcelTAD
Home › Scala › Scala Try

Scala Try

Some code throws exceptions you cannot avoid: parsing numbers, reading files, calling Java libraries. Scala lets you handle them in two ways — the classic try/catch expression, and the Try[A] type, which turns an exception into an ordinary value: Success(result) or Failure(exception).

try / catch / finally

In Scala, try is an expression: it returns the value of the try block or of the matching catch case. The catch block uses pattern matching.

scala · try it yourself
def toNumber(s: String): Int =
  try s.trim.toInt
  catch
    case _: NumberFormatException => -1

@main def run(): Unit =
  println(toNumber(" 42 "))
  println(toNumber("forty-two"))

  val result =
    try
      val data = Array(1, 2, 3)
      data(10)
    catch
      case e: ArrayIndexOutOfBoundsException => println(s"caught: ${e.getMessage}"); 0
    finally
      println("finally always runs")
  println(result)
42
-1
caught: Index 10 out of bounds for length 3
finally always runs
0

finally runs whether or not an exception happened; use it for cleanup. Its value is ignored.

Throwing exceptions

Use throw with any Throwable. The handy require method throws an IllegalArgumentException when a condition fails.

scala · try it yourself
def sqrt(x: Double): Double =
  if x < 0 then throw IllegalArgumentException(s"negative input: $x")
  math.sqrt(x)

def percent(p: Int): String =
  require(p >= 0 && p <= 100, s"percent out of range: $p")
  s"$p%"

@main def run(): Unit =
  println(sqrt(16))
  try sqrt(-1)
  catch case e: IllegalArgumentException => println(e.getMessage)
  try percent(140)
  catch case e: IllegalArgumentException => println(e.getMessage)
4.0
negative input: -1.0
requirement failed: percent out of range: 140

The Try type

Try(expression) evaluates the expression and captures any non-fatal exception. The result is a value you can pass around, transform and combine.

scala · try it yourself
import scala.util.{Try, Success, Failure}

@main def run(): Unit =
  val good = Try("123".toInt)
  val bad = Try("12x".toInt)
  println(good)
  println(bad)

  bad match
    case Success(n) => println(s"parsed $n")
    case Failure(e) => println(s"failed: ${e.getClass.getSimpleName}")

  println(good.map(_ * 2))
  println(bad.map(_ * 2).getOrElse(0))
  println(bad.recover { case _: NumberFormatException => -1 })
  println(good.toOption)
  println(bad.toEither.left.map(_.getMessage))
Success(123)
Failure(java.lang.NumberFormatException: For input string: "12x")
failed: NumberFormatException
Success(246)
0
Success(-1)
Some(123)
Left(For input string: "12x")

Chaining Try with for

Like Option and Either, Try works in for comprehensions. The first failure short-circuits the rest.

scala · try it yourself
import scala.util.Try

def parse(s: String): Try[Int] = Try(s.toInt)
def safeDiv(a: Int, b: Int): Try[Int] = Try(a / b)

@main def run(): Unit =
  def compute(x: String, y: String) =
    for
      a <- parse(x)
      b <- parse(y)
      q <- safeDiv(a, b)
    yield q

  println(compute("84", "2"))
  println(compute("84", "0"))
  println(compute("eighty", "2"))
Success(42)
Failure(java.lang.ArithmeticException: / by zero)
Failure(java.lang.NumberFormatException: For input string: "eighty")

Useful Try methods

Method Effect
map, flatMap transform a Success; a Failure passes through
getOrElse(default) value or default
recover { case e: X => v } turn matching failures into a success
recoverWith { case e => Try(...) } like recover, but with another Try
toOption drop the exception
toEither Right(value) or Left(throwable)
fold(e => …, v => …) handle both cases
isSuccess / isFailure test the outcome

Cleaning up resources: Using

scala.util.Using opens a resource, runs your code and always closes the resource, returning a Try.

scala · try it yourself
import scala.util.Using
import java.io.{BufferedReader, StringReader}

@main def run(): Unit =
  val firstLine = Using(BufferedReader(StringReader("line one\nline two"))) { reader =>
    reader.readLine()
  }
  println(firstLine)
Success(line one)

Try, Either or exceptions?

Use… When…
try/catch at the edges of your program, around code that throws
Try wrapping Java or library calls that throw, then working with values
Either your own business errors with meaningful error types
plain exceptions truly unexpected bugs that should stop the program

Note: Try only catches non-fatal exceptions. Errors like OutOfMemoryError are deliberately not captured.

Test yourself

What does Try("abc".toInt) evaluate to?

  1. 0
  2. None
  3. A Failure containing a NumberFormatException
  4. It throws immediately

When does a finally block run?

  1. Only when an exception was thrown
  2. Only when no exception was thrown
  3. Always
  4. Never in Scala 3

Which method turns certain failures back into a success?

  1. map
  2. recover
  3. toOption
  4. flatten