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

Exception के Types

Exception types अलग-अलग तरह की समस्याएं हैं, जैसे fire alarm बनाम flood alarm, हर एक का नाम उसके गलत होने के हिसाब से। सही वाला catch करने के लिए चुनना आपको सही से react करने देता है।

In this page:

  1. Exception Types
Syntax
csharp
try
{
    // code
}
catch (SpecificException ex)   // e.g. DivideByZeroException
{
    Console.WriteLine(ex.Message);
}
catch (Exception ex)           // general handler last
{
}

Exception Types

C# में ArgumentException, NullReferenceException, और DivideByZeroException जैसी built-in exception types की एक hierarchy है, सभी System.Exception से derive होती हैं।

पहले एक ज़्यादा specific type catch करना आपको अलग failures को अलग तरीके से handle करने देता है। एक catch-all catch (Exception ex) को आमतौर पर आखिर में आना चाहिए।

Note: catch blocks को सबसे specific से सबसे general तक order करें — compiler संबंधित types के लिए इसे enforce करता है।

उदाहरण: Exception Types

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            Console.WriteLine(a / b);
        }
        catch (DivideByZeroException ex)
        {
            Console.WriteLine("Division error: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("General error: " + ex.Message);
        }
    }
}
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. base Exception catch करना जब एक specific type आपको हर case सही से handle करने देती।
  2. ArgumentNullException को NullReferenceException के साथ confuse करना।
  3. यह न जानना कि IndexOutOfRangeException और DivideByZeroException runtime exceptions हैं जिन्हें आप checks से रोक सकते हैं।
🔒

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.