0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Option, Try, Either for Errors

Implement robust error handling using `Option` for absence of value, `Try` for exceptions, and `Either` for distinct failure/success paths.

Option, Try, Either for Errors is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 of 3. 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 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Handling Errors Gracefully

In programming, things don't always go as planned. Files might not exist, network requests could fail, or calculations might lead to invalid results.

  • How do we write robust code that can handle these situations gracefully?
  • Scala provides powerful tools to manage errors and missing values without resorting to `null` or throwing exceptions everywhere.

The Problem with Null

Many languages use null to represent the absence of a value. However, null is a common source of bugs like the dreaded NullPointerException.

Scala discourages the use of null. Instead, it offers types that explicitly state whether a value might be missing, making your code safer and easier to understand.

Introducing Scala Option

Option[A] is a container that can hold either a value of type A (represented by Some[A]) or no value at all (represented by None).

  • It forces you to consider the case where a value might be absent.
  • This prevents unexpected NullPointerExceptions and makes your code more explicit.

Option in Action: Some & None

Let's see how Option works. We'll define a function that might return a name or might not, depending on an ID.

object Main {
  def findUser(id: Int): Option[String] = {
    if (id == 1) Some("Alice")
    else None
  }

  def main(args: Array[String]): Unit = {
    val user1 = findUser(1) // Some("Alice")
    val user2 = findUser(2) // None

    println(s"User 1: $user1")
    println(s"User 2: $user2")
  }
}

Working with Option: map & getOrElse

You can transform the value inside an Option using map, or provide a default value if it's None using getOrElse.

object Main {
  def findUser(id: Int): Option[String] = {
    if (id == 1) Some("Alice")
    else None
  }

  def main(args: Array[String]): Unit = {
    val userGreeting = findUser(1).map(name => s"Hello, $name!")
    val defaultGreeting = findUser(2).map(name => s"Hello, $name!").getOrElse("Hello, Guest!")

    println(s"User greeting: $userGreeting")
    println(s"Default greeting: $defaultGreeting")
  }
}

Introducing Scala Try

While Option handles missing values, Try[A] is designed to handle computations that might throw an exception.

  • A Try can be either a Success[A] (if the computation completes normally) or a Failure[Throwable] (if an exception occurs).
  • It encapsulates exceptions, allowing you to deal with them functionally.

Try in Action: Success & Failure

Let's define a function that might throw an exception (e.g., division by zero) and wrap its execution in a Try.

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

object Main {
  def divide(a: Int, b: Int): Try[Int] = Try {
    a / b
  }

  def main(args: Array[String]): Unit = {
    val result1 = divide(10, 2) // Success(5)
    val result2 = divide(10, 0) // Failure(java.lang.ArithmeticException: / by zero)

    println(s"Result 1: $result1")
    println(s"Result 2: $result2")
  }
}

Working with Try: recover & fold

Try offers methods like recover to handle specific exceptions or fold to process both success and failure cases cleanly.

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

object Main {
  def parseNumber(s: String): Try[Int] = Try(s.toInt)

  def main(args: Array[String]): Unit = {
    val num1 = parseNumber("123").getOrElse(0)
    val num2 = parseNumber("abc").getOrElse(0)

    val message = parseNumber("456").fold(
      ex => s"Failed to parse: ${ex.getMessage}",
      num => s"Parsed number: $num"
    )

    println(s"Parsed num1: $num1")
    println(s"Parsed num2: $num2")
    println(s"Message: $message")
  }
}

Introducing Scala Either

Either[L, R] is a type that represents one of two possible values. By convention:

  • Left[L] represents a failure (or error type L).
  • Right[R] represents a success (or result type R).

Unlike Try, Either allows you to specify a meaningful type for your error, not just a Throwable.

Either in Action: Left & Right

Here's a function that validates an email. It returns either a String error message (Left) or the validated email (Right).

object Main {
  def validateEmail(email: String): Either[String, String] = {
    if (email.contains("@") && email.contains(".")) Right(email)
    else Left("Invalid email format")
  }

  def main(args: Array[String]): Unit = {
    val email1 = validateEmail("test@example.com") // Right("test@example.com")
    val email2 = validateEmail("invalid-email")   // Left("Invalid email format")

    println(s"Email 1: $email1")
    println(s"Email 2: $email2")
  }
}

Quick Check: Error Handling

You are writing a function that reads a configuration value from a map. If the key exists, you want to convert its string value to an integer. If the key is missing or the conversion fails, you want to return a default value of 0.

Which combination of Scala types and methods would be most appropriate for this task?

Recap: Option, Try, Either

We've explored three powerful Scala types for robust error handling:

  • Option[A]: For handling the absence of a value (Some[A] or None).
  • Try[A]: For encapsulating computations that might throw exceptions (Success[A] or Failure[Throwable]).
  • Either[L, R]: For representing two distinct outcomes, typically a failure type L and a success type R (Left[L] or Right[R]).

Using these types makes your Scala code safer, more explicit, and more functional!

Frequently asked questions

Is the “Option, Try, Either for Errors” lesson free?

Yes — the full text of “Option, Try, Either for Errors” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 3 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 “Option, Try, Either for Errors”?

Implement robust error handling using `Option` for absence of value, `Try` for exceptions, and `Either` for distinct failure/success paths. 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 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Option, Try, Either for Errors” 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. Immutable Collections Deep Dive
  2. Functional Operations on Collections
  3. Option, Try, Either for Errors
← Back to Scala for Backend Engineering & Functional Programming