Exception के Types
Exception types अलग-अलग तरह की समस्याएं हैं, जैसे fire alarm बनाम flood alarm, हर एक का नाम उसके गलत होने के हिसाब से। सही वाला catch करने के लिए चुनना आपको सही से react करने देता है।
In this page:
Syntax
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
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);
}
}
}
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. #}
आम गलतियां
- base
Exceptioncatch करना जब एक specific type आपको हर case सही से handle करने देती। ArgumentNullExceptionकोNullReferenceExceptionके साथ confuse करना।- यह न जानना कि
IndexOutOfRangeExceptionऔरDivideByZeroExceptionruntime exceptions हैं जिन्हें आप checks से रोक सकते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: