← Back to Kotlin Course | Chapter 13: Error Handling & Testing | Lesson 1 of 6

try, catch, finally का उपयोग

try, catch, और finally आपके program को कुछ risky आज़माने देते हैं, गलत होने पर recover करने देते हैं, और चाहे जो भी हो आखिर में साफ़-सफ़ाई करने देते हैं।
Syntax
kotlin
try {
    // risky code
} catch (e: ExceptionType) {
    // handle it
} catch (e: OtherException) {
    // handle differently
} finally {
    // always runs
}

Catching an Exception

risky code को try { } में wrap करना और उसके बाद catch (e: ExceptionType) { } program को crash होने के बजाय जब वह specific तरह का exception हो तो सुंदरता से recover करने देता है।

उदाहरण: Catching an Exception

markup
// Entry point: execution of the program starts here
fun main() {
    try {
        // Declare a read-only variable `result`, set to `10 / 0`
        val result = 10 / 0
        // Print `result` to the console, with a trailing newline
        println(result)
    } catch (e: ArithmeticException) {
        // Print "Caught an error: ${e.message}" to the console, with a trailing newline
        println("Caught an error: ${e.message}")
    }
}

Using finally for Cleanup

एक finally { } block हमेशा try/catch के बाद execute होता है, चाहे exception फेंका या पकड़ा गया हो या नहीं, इसे cleanup code के लिए सही जगह बनाते हुए जिसे हमेशा चलना चाहिए।

उदाहरण: Using finally for Cleanup

markup
// Entry point: execution of the program starts here
fun main() {
    try {
        // Print "Attempting risky operation" to the console, with a trailing newline
        println("Attempting risky operation")
        throw RuntimeException("Something failed")
    } catch (e: RuntimeException) {
        // Print "Handled: ${e.message}" to the console, with a trailing newline
        println("Handled: ${e.message}")
    } finally {
        // Print "Cleanup always runs" to the console, with a trailing newline
        println("Cleanup always runs")
    }
}

Multiple catch Blocks

कई catch blocks को अलग exception types को अलग तरीके से handle करने के लिए chain किया जा सकता है, और Kotlin उन्हें उसी order में जांचता है जिसमें वे लिखे गए हैं, पहली matching type उपयोग करते हुए।

उदाहरण: Multiple catch Blocks

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `values`, set to `listOf("10", "abc", "5")`
    val values = listOf("10", "abc", "5")
    // Loop over `values`, binding each item to `value`
    for (value in values) {
        try {
            // Print "Parsed: ${value.toInt()}" to the console, with a trailing newline
            println("Parsed: ${value.toInt()}")
        } catch (e: NumberFormatException) {
            // Print "Not a number: $value" to the console, with a trailing newline
            println("Not a number: $value")
        }
    }
}

try as an Expression

चूंकि try को एक expression की तरह उपयोग किया जा सकता है, चाहे जो भी branch execute हो -- try या catch -- उसकी value सीधे किसी variable को assign की जा सकती है।

उदाहरण: try as an Expression

markup
// Define the function `parseOrDefault` taking `text` and returning an Int
fun parseOrDefault(text: String): Int {
    // Return `try {` from this function
    return try {
        text.toInt()
    } catch (e: NumberFormatException) {
        -1
    }
}

// Entry point: execution of the program starts here
fun main() {
    // Print `parseOrDefault("42")` to the console, with a trailing newline
    println(parseOrDefault("42"))
    // Print `parseOrDefault("oops")` to the console, with a trailing newline
    println(parseOrDefault("oops"))
}
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. Exception जैसी बहुत व्यापक type को हर जगह catch करना, उन bugs को छुपाते हुए जिन्हें चुपचाप निगलने के बजाय ठीक किया जाना चाहिए था।
  2. यह भूल जाना कि finally हमेशा चलता है, भले ही try या catch block जल्दी return कर दे, जो इसे cleanup के लिए उपयोग करने का बिल्कुल यही मकसद है।
  3. यह न समझना कि try को एक expression की तरह उपयोग किया जा सकता है, चाहे जो भी branch असल में चले उससे एक value produce करते हुए।
चैप्टर सारांश
  • try { } उस code को wrap करता है जो exception फेंक सकता है; catch (e: Type) { } अगर कोई हो तो एक specific exception type को handle करता है।
  • finally { } हमेशा try/catch के बाद चलता है, चाहे कोई exception फेंका गया हो या नहीं, इसे cleanup के लिए आदर्श बनाते हुए।
  • कई catch blocks अलग exception types को अलग तरीके से handle कर सकते हैं, ऊपर से नीचे order में जांचे जाते हुए।
  • try को एक expression की तरह उपयोग किया जा सकता है, जिसमें resulting value जो भी branch (try या catch) असल में चले उससे आती है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 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.