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

Ngoại lệ tùy chỉnh (Custom Exceptions) trong C#

Trong C#, bạn có thể tạo ngoại lệ do người dùng định nghĩa (user-defined exception). Lớp exception tùy chỉnh kế thừa từ Exception. Custom exception = user-defined exception.

Ví dụ: Ngoại lệ nhiệt độ bằng 0

using System;

namespace Demo
{
    // Custom exception
    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);
        }
    }
    
    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();
        }
    }
}

Kết quả

TempIsZeroException: Zero Temperature found

Best practices:

  • Kế thừa từ Exception (hoặc ApplicationException cũ).
  • Đặt tên kết thúc bằng Exception.
  • Cung cấp 3 constructor: default, message, message + innerException.
  • Đánh dấu [Serializable] nếu cần serialize.
  • Override ToString() nếu cần format đặc biệt.