0Pricing
Scala for Backend Engineering & Functional Programming · Leçon

Option, Try et Either pour gérer les erreurs

Mettez en œuvre une gestion robuste des erreurs en utilisant `Option` pour l’absence de valeur, `Try` pour les exceptions et `Either` pour distinguer les chemins d’échec et de réussite.

Option, Try et Either pour gérer les erreurs est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 3 sur 3. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 3 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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!

Questions Fréquemment Posées

La leçon « Option, Try et Either pour gérer les erreurs » est-elle gratuite ?

Oui — le texte complet de « Option, Try et Either pour gérer les erreurs » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 3 leçons au total.

Qu'est-ce que j'apprendrai dans « Option, Try et Either pour gérer les erreurs » ?

Mettez en œuvre une gestion robuste des erreurs en utilisant `Option` pour l’absence de valeur, `Try` pour les exceptions et `Either` pour distinguer les chemins d’échec et de réussite. Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?

Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 3.

Combien de temps prend la leçon « Option, Try et Either pour gérer les erreurs » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?

Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Exploration approfondie des collections immuables
  2. Opérations fonctionnelles sur les collections
  3. Option, Try et Either pour gérer les erreurs
← Retour à Scala for Backend Engineering & Functional Programming