किसी भी अन्य प्रोग्रामिंग भाषा की तरह, सी # में, आप आसानी से उपयोगकर्ता द्वारा परिभाषित अपवाद बना सकते हैं। उपयोगकर्ता द्वारा परिभाषित अपवाद वर्ग अपवाद वर्ग से प्राप्त होते हैं। कस्टम अपवाद वे हैं जिन्हें हम उपयोगकर्ता-परिभाषित अपवाद कहते हैं।
नीचे दिए गए उदाहरण में, बनाया गया अपवाद अंतर्निर्मित अपवाद नहीं है; यह एक कस्टम अपवाद है -
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