เหมือนภาษาอื่นๆ ใน C# สามารถสร้าง Exception แบบกำหนดเองได้ง่าย คลาส Exception แบบกำหนดเองสืบทอดจากคลาส Exception
ในตัวอย่าง Exception ที่สร้างไม่ใช่ Built-in exception:
TempIsZeroException
ตัวอย่าง
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