किसी अन्य प्रोग्रामिंग भाषा की तरह, C# में आप आसानी से यूजर-डिफाइंड एक्सेप्शन बना सकते हैं। यूजर-डिफाइंड एक्सेप्शन क्लासेस Exception क्लास से डेराइव्ड होती हैं। कस्टम एक्सेप्शन्स को यूजर-डिफाइंड एक्सेप्शन्स कहा जाता है।
नीचे दिए गए उदाहरण में, बनाया गया एक्सेप्शन बिल्ट-इन एक्सेप्शन नहीं है; यह एक कस्टम एक्सेप्शन है -
TempIsZeroException
आप C# में यूजर-डिफाइंड एक्सेप्शन बनाने का तरीका जानने के लिए निम्नलिखित कोड आज़मा सकते हैं -
उदाहरण
using System;
namespace Demo {
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();
}
}
}
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);
}
}
}
आउटपुट
TempIsZeroException: Zero Temperature found