Ngoại lệ là vấn đề phát sinh khi chạy chương trình. Ngoại lệ C# phản ứng với tình huống ngoại lệ như chia cho 0.
Định nghĩa ngoại lệ riêng: lớp ngoại lệ do người dùng định nghĩa kế thừa từ lớp Exception.
Ví dụ
using System;
namespace UserDefinedException {
class TestFitness {
static void Main(string[] args) {
Fitness f = new Fitness();
try {
f.showResult();
} catch(FitnessTestFailedException e) {
Console.WriteLine("Ngoại lệ tự định nghĩa: {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!");
}
}
}
Ngoại lệ tự định nghĩa:
public class FitnessTestFailedException : Exception {
public FitnessTestFailedException(string message) : base(message) { }
}