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

Success and Failure

Success holds the answer when a job worked, and Failure holds the problem when it did not. Together they are the two results a Try can give.

In this page:

  1. Success and Failure
Syntax
scala
import scala.util.{Try, Success, Failure}
Try(risky_expression) match {
  case Success(value)     => expression
  case Failure(exception) => expression
}

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}")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to import scala.util.{Try, Success, Failure}, so the names are not found.
  2. Matching only Success and forgetting Failure, so a failed result throws a MatchError.
  3. Ignoring the exception in Failure(e), so the reason for the error is lost.
🔒

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.