เช่นเดียวกับภาษาการเขียนโปรแกรมอื่นๆ ใน C# คุณสามารถสร้างข้อยกเว้นที่ผู้ใช้กำหนดเองได้อย่างง่ายดาย คลาสข้อยกเว้นที่ผู้ใช้กำหนดได้มาจากคลาสข้อยกเว้น ข้อยกเว้นที่กำหนดเองคือสิ่งที่เราเรียกว่าข้อยกเว้นที่ผู้ใช้กำหนดเอง
ในตัวอย่างด้านล่าง ข้อยกเว้นที่สร้างขึ้นไม่ใช่ข้อยกเว้นในตัว มันเป็นข้อยกเว้นที่กำหนดเอง -
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