परिचय
C# में सभी एक्सेप्शन क्लासेस System.Exception से प्रत्यक्ष या अप्रत्यक्ष रूप से प्राप्त होती हैं। आप अपनी खुद की एक्सेप्शन क्लास बना सकते हैं जो Exception से इनहेरिट करती हो।
उदाहरण: तापमान शून्य होने पर एक्सेप्शन फेंकना
using System;
namespace UserDefinedException
{
// कस्टम एक्सेप्शन क्लास
public class TempIsZeroException : Exception
{
public TempIsZeroException(string message) : base(message) { }
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if (temperature == 0)
{
throw new TempIsZeroException("Zero Temperature found");
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch (TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
मुख्य बिंदु
- कस्टम एक्सेप्शन क्लास का नाम
Exceptionसे समाप्त होना चाहिए (कन्वेंशन)। - कंस्ट्रक्टर में
base(message)कॉल करें। throwकीवर्ड से एक्सेप्शन फेंकें।try-catchब्लॉक में पकड़ें।