ข้อยกเว้นคือปัญหาที่เกิดขึ้นระหว่างการทำงานของโปรแกรม ข้อยกเว้น C# เป็นการตอบสนองต่อสถานการณ์พิเศษที่เกิดขึ้นในขณะที่โปรแกรมกำลังทำงานอยู่ เช่น การพยายามหารด้วยศูนย์
กำหนดข้อยกเว้นของคุณเอง คลาสข้อยกเว้นที่ผู้ใช้กำหนดได้มาจากคลาสข้อยกเว้น
ต่อไปนี้เป็นตัวอย่าง −
ตัวอย่าง
using System;
namespace UserDefinedException {
class TestFitness {
static void Main(string[] args) {
Fitness f = new Fitness();
try {
f.showResult();
} catch(FitnessTestFailedException e) {
Console.WriteLine("User defined exception: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class FitnessTestFailedException: Exception {
public FitnessTestFailedException(string message): base(message) {
}
}
public class Fitness {
int points = 0;
public void showResult() {
if(points < 110) {
throw (new FitnessTestFailedException("Player failed the fitness test!"));
} else {
Console.WriteLine("Player passed the fitness test!");
}
}
} ด้านบน เราได้สร้างข้อยกเว้นที่ผู้ใช้กำหนด -
public class FitnessTestFailedException: Exception {
public FitnessTestFailedException(string message): base(message) {
}