परिचय
C# में एक्सेप्शन हैंडलिंग try, catch, finally ब्लॉक्स के साथ की जाती है।
कीवर्ड्स
try: संरक्षित कोड ब्लॉक।catch: विशिष्ट एक्सेप्शन पकड़ना।finally: हमेशा निष्पादित (क्लीनअप)।
उदाहरण: शून्य से विभाजन
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
public void Division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e.Message);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.Division(25, 0);
Console.ReadKey();
}
}
}
आउटपुट
Exception caught: Attempted to divide by zero. Result: 0
महत्वपूर्ण बिंदु
finallyब्लॉक हमेशा चलता है (return, break, continue के बाद भी)।- एकाधिक
catchब्लॉक: विशिष्ट से सामान्य क्रम में। catchबिना टाइप के सभी पकड़ता है (अनुशंसित नहीं)।usingस्टेटमेंटIDisposableके लिएfinallyका सिंटैक्टिक शुगर है।