सी # अपवाद कक्षाओं द्वारा दर्शाए जाते हैं। C# में अपवाद वर्ग मुख्य रूप से प्रत्यक्ष या अप्रत्यक्ष रूप से System.Exception वर्ग से प्राप्त होते हैं।
आप अपना खुद का अपवाद भी परिभाषित कर सकते हैं। उपयोगकर्ता-परिभाषित अपवाद वर्ग अपवाद वर्ग से प्राप्त होते हैं।
निम्नलिखित एक उदाहरण है -
उदाहरण
using System;
namespace UserDefinedException {
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);
}
}
}