Success और Failure
Success जवाब रखता है जब कोई काम सफल हुआ, और Failure समस्या रखता है जब नहीं हुआ। साथ में वे वे दो results हैं जो एक Try दे सकता है।
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) और 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
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. #}
आम गलतियां
scala.util.{Try, Success, Failure}import करना भूल जाना, जिससे names नहीं मिलते।- सिर्फ
Successmatch करना औरFailureभूल जाना, जिससे एक failed resultMatchErrorफेंकता है। Failure(e)में exception को नज़रअंदाज़ करना, जिससे error का कारण खो जाता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: