← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 5 of 7

Success and Failure

In this page:

  1. Success and Failure

Success and Failure

Success(value) and Failure(exception) are Try's two possible outcomes, matched with pattern matching just like Some/None. .getOrElse and .map work on Try the same way they do on Option, transforming a Success's value while leaving a Failure unchanged. This lets you write error-handling code that reads much like ordinary Option-based code.

Note: Try's map/getOrElse/pattern-matching API deliberately mirrors Option's, so switching between the two feels familiar.

Example: Success and Failure

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

object Main extends App {
  val results = List(Try(10 / 2), Try(10 / 0))

  results.foreach {
    case Success(value) => println(s"Got: $value")
    case Failure(ex) => println(s"Failed: ${ex.getClass.getSimpleName}")
  }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.