Try Type क्या है
एक Try किसी ऐसे काम को wrap करता है जो crash हो सकता है ताकि crash एक सामान्य जवाब बन जाए जिसे आप जांच सकें। यह एक helmet जैसा है जो गिरने को रोक देता है ताकि game चलता रहे।
In this page:
Syntax
import scala.util.Try
val result = Try(risky_expression)
val value = result.getOrElse(default_value)
The Try Type
Try[T] एक ऐसे computation को represent करता है जो exception फेंक सकता है, result को बिना uncaught exception को propagate होने दिए Success(value) या Failure(exception) के रूप में wrap करता है।
Try(riskyExpression) expression चलाता है और किसी भी exception को एक Failure में पकड़ लेता है। यह exception handling को एक explicit, type-visible value में बदल देता है जिसे आप transform और check कर सकते हैं, Option से मिलती-जुलती भावना में।
Note:
Try(expression) एक explicit try/catch block लिखे बिना किसी risky operation को Success/Failure value में convert करने का एक संक्षिप्त तरीका है।
उदाहरण: The Try Type
import scala.util.Try
object Main extends App {
val result: Try[Int] = Try(10 / 2)
val failure: Try[Int] = Try(10 / 0)
println(result)
println(failure)
}
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. #}
आम गलतियां
- सिर्फ code के चारों ओर
try/catchका उपयोग करना जबTryपहले से exception कोFailureमें capture कर लेता है। - किसी
Failureपर.getcall करना, जो exception को फिर से फेंक देता है। - यह मान लेना कि
Tryसब कुछ पकड़ लेता है, जबकि यहOutOfMemoryErrorजैसी fatal errors नहीं पकड़ता।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: