C# ব্যতিক্রমগুলি ক্লাস দ্বারা প্রতিনিধিত্ব করা হয়। 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);
}
}
}