0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Try, Success, Failure

Exception handling.

Try, Success, Failure is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)
}

Success and Failure

A Try that completes normally is a Success holding the value; one that throws becomes a Failure holding the exception.

import scala.util.{Try, Success, Failure}

@main def run(): Unit = {
  val result = Try("123".toInt)
  result match {
    case Success(n) => println(s"parsed: $n")
    case Failure(e) => println(s"failed: ${e.getMessage}")
  }
}

Pattern Matching Failures

When the wrapped code throws, you can inspect the exception inside Failure. Here a bad parse is captured cleanly.

import scala.util.{Try, Success, Failure}

@main def run(): Unit = {
  val result = Try("abc".toInt)
  result match {
    case Success(n) => println(s"got $n")
    case Failure(e) => println(s"error type: ${e.getClass.getSimpleName}")
  }
}

getOrElse with Try

getOrElse returns the success value or a default when the Try failed. This avoids throwing entirely.

import scala.util.Try

@main def run(): Unit = {
  val n = Try("oops".toInt).getOrElse(-1)
  println(n)
}

map on Try

map transforms a Success value. If the original is a Failure, or if the mapping function throws, the result stays a Failure.

import scala.util.Try

@main def run(): Unit = {
  val doubled = Try("21".toInt).map(_ * 2)
  val failed  = Try("x".toInt).map(_ * 2)
  println(doubled)
  println(failed)
}

recover: Handle the Exception

recover lets you turn a Failure back into a Success by handling specific exceptions with a partial function.

import scala.util.Try

@main def run(): Unit = {
  val safe = Try("x".toInt).recover {
    case _: NumberFormatException => 0
  }
  println(safe)
}

recoverWith

recoverWith is like recover, but the handler returns another Try instead of a plain value. Use it when recovery itself might fail.

import scala.util.Try

@main def run(): Unit = {
  val result = Try("x".toInt).recoverWith {
    case _: NumberFormatException => Try("42".toInt)
  }
  println(result)
}

toEither and toOption

Try converts cleanly to other error types:

  • toOption: Success becomes Some, Failure becomes None.
  • toEither: Success becomes Right, Failure becomes Left(throwable).
import scala.util.Try

@main def run(): Unit = {
  println(Try("5".toInt).toOption)
  println(Try("x".toInt).toOption)
  println(Try("5".toInt).toEither.isRight)
}

Chaining with flatMap

flatMap sequences computations that each return a Try. If any step fails, the whole chain short-circuits to that Failure.

import scala.util.Try

object Main {
  def half(n: Int): Try[Int] = Try(if (n % 2 == 0) n / 2 else throw new RuntimeException("odd"))

  def main(args: Array[String]): Unit = {
    println(Try("8".toInt).flatMap(half))
    println(Try("7".toInt).flatMap(half))
  }
}

Try vs try/catch

Try turns exceptions into values, so you can map, flatMap, and combine results without nested try/catch blocks. It only catches non-fatal exceptions; serious errors like OutOfMemoryError still propagate.

Quick Check

Test your knowledge of Try.

Recap

You learned exception handling with Try:

  • Try { ... } captures non-fatal exceptions as Failure, normal results as Success.
  • Transform with map/flatMap; recover with recover/recoverWith.
  • Provide defaults with getOrElse.
  • Convert with toOption and toEither.

Frequently asked questions

Is the “Try, Success, Failure” lesson free?

Yes — the full text of “Try, Success, Failure” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Try, Success, Failure”?

Exception handling. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Try, Success, Failure” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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