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

Ngoại lệ do người dùng định nghĩa (User-defined Exceptions) trong C#

Giống như ngôn ngữ khác, trong C# bạn dễ dàng tạo user-defined exception. Lớp exception tùy chỉnh kế thừa từ class Exception. Custom exceptions là user-defined exceptions.

Trong ví dụ dưới, exception tạo không phải built-in; là custom exception:

TempIsZeroException

Thử chạy code sau để học tạo user-defined exception trong C#:

Ví dụ

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

Kết quả

TempIsZeroException: Zero Temperature found