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:
Syntax
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
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}")
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting to import
scala.util.{Try, Success, Failure}, so the names are not found. - Matching only
Successand forgettingFailure, so a failed result throws aMatchError. - 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: