0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Try, Success, Failure

Exception handling.

What is Try?

Try[T] represents a computation that may either result in a value or throw an exception. It has two subtypes:

  • Success[T] wraps a normal result.
  • Failure wraps a Throwable.

It turns exception-throwing code into a value you can compose.

Importing Try

Try lives in scala.util. You wrap any expression that might throw inside Try { ... } and it catches non-fatal exceptions for you.

import scala.util.Try

@main def run(): Unit = {
  val ok = Try(10 / 2)
  val bad = Try(10 / 0)
  println(ok)
  println(bad)
}

All lessons in this course

  1. Either for Errors
  2. Try, Success, Failure
  3. Composing Either
  4. Converting Between Types
← Back to Scala for Backend Engineering & Functional Programming