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

Success और Failure

Success जवाब रखता है जब कोई काम सफल हुआ, और Failure समस्या रखता है जब नहीं हुआ। साथ में वे वे दो results हैं जो एक Try दे सकता है।

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) और Failure(exception), Try के दो संभावित outcomes हैं, जिन्हें Some/None की तरह ही pattern matching से match किया जाता है।

.getOrElse और .map, Try पर वैसे ही काम करते हैं जैसे Option पर, किसी Success की value को transform करते हुए Failure को बिना बदले छोड़ देते हैं। यह आपको error-handling code ऐसे लिखने देता है जो साधारण Option-based code जैसा ही पढ़ा जाता है।

Note: Try का map/getOrElse/pattern-matching API जानबूझकर Option के जैसा है, इसलिए दोनों के बीच switch करना परिचित लगता है।

उदाहरण: 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. #}
आम गलतियां
  1. scala.util.{Try, Success, Failure} import करना भूल जाना, जिससे names नहीं मिलते।
  2. सिर्फ Success match करना और Failure भूल जाना, जिससे एक failed result MatchError फेंकता है।
  3. Failure(e) में exception को नज़रअंदाज़ करना, जिससे error का कारण खो जाता है।
🔒

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.