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

Try Type क्या है

एक Try किसी ऐसे काम को wrap करता है जो crash हो सकता है ताकि crash एक सामान्य जवाब बन जाए जिसे आप जांच सकें। यह एक helmet जैसा है जो गिरने को रोक देता है ताकि game चलता रहे।

In this page:

  1. The Try Type
Syntax
scala
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

markup
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)
}
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. सिर्फ code के चारों ओर try / catch का उपयोग करना जब Try पहले से exception को Failure में capture कर लेता है।
  2. किसी Failure पर .get call करना, जो exception को फिर से फेंक देता है।
  3. यह मान लेना कि Try सब कुछ पकड़ लेता है, जबकि यह OutOfMemoryError जैसी fatal errors नहीं पकड़ता।
🔒

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.