किसी अन्य प्रोग्रामिंग भाषा की तरह, 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