← Back to C# Course | Chapter 10: Exception Handling | Lesson 1 of 6

try / catch / finally कैसे काम करता है

try, catch, और finally एक safety net हैं: कुछ risky आज़माएं, गिरने पर समस्या पकड़ें, और आखिर में चाहे जो भी हो साफ़-सफ़ाई करें। यह आपके program को crash होने से बचाता है।

In this page:

  1. try / catch / finally
Syntax
csharp
try
{
    // code that might throw
}
catch (ExceptionType ex)
{
    // handle the error
}
finally
{
    // always runs
}

try / catch / finally

एक try block में ऐसा code होता है जो exception फेंक सकता है; एक matching catch block अगर कोई हो तो उसे handle करता है।

finally बाद में चलता है चाहे कोई exception फेंका गया हो या नहीं, इसे cleanup code के लिए सही जगह बनाते हुए। Execution exception के point से सीधे सबसे नज़दीकी matching catch पर jump करता है।

Note: finally तब भी चलता है जब try या catch block में एक return statement हो।

उदाहरण: try / catch / finally

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine(numbers[5]);
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("Caught: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Cleanup complete");
        }
    }
}
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 catch करना और catch block को खाली छोड़ देना, जो असली errors छुपाता है।
  2. specific catches से पहले एक general catch (Exception) रखना, जो एक compile error है।
  3. हमेशा चलना चाहिए वाले code को finally के बजाय try में रखना।
🔒

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.