Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Ngoại lệ tùy chỉnh (Custom Exception) do người dùng định nghĩa trong C#

Các ngoại lệ trong C# được biểu diễn bằng các lớp, kế thừa trực tiếp hoặc gián tiếp từ System.Exception. Bạn có thể tự định nghĩa ngoại lệ riêng bằng cách kế thừa từ lớp Exception.

Ví dụ

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);
        }
    }
}