Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

User-Defined Exceptions (Exception แบบกำหนดเอง) ใน C#

User-Defined Exceptions (Custom Exceptions) สร้างโดย繼承จาก Exception Class ใช้สำหรับ Business Logic Errors เฉพาะ Domain

ขั้นตอนสร้าง

  1. สร้าง Class 繼承 Exception
  2. เพิ่ม Constructor ต่างๆ
  3. เพิ่ม Properties/Methods ตามต้องการ
  4. (Optional) Implement ISerializable สำหรับ Serialization

ตัวอย่าง: TempIsZeroException

using System;

// Custom Exception
public class TempIsZeroException : Exception
{
    public TempIsZeroException() : base() { }
    public TempIsZeroException(string message) : base(message) { }
    public TempIsZeroException(string message, Exception inner) : base(message, inner) { }
    
    // เพิ่ม Property เฉพาะ Domain
    public double TemperatureValue { get; set; }
}

// ใช้งาน
public class Temperature
{
    public double Value { get; private set; }
    
    public void ShowTemp()
    {
        if (Value == 0)
            throw new TempIsZeroException("Zero Temperature found") 
            { 
                TemperatureValue = Value 
            };
        
        Console.WriteLine("Temperature: {0}", Value);
    }
}

class Program
{
    static void Main()
    {
        Temperature temp = new Temperature { Value = 0 };
        
        try
        {
            temp.ShowTemp();
        }
        catch (TempIsZeroException e)
        {
            Console.WriteLine("Custom Exception: {0}", e.Message);
            Console.WriteLine("Temp Value: {0}", e.TemperatureValue);
        }
        catch (Exception e)
        {
            Console.WriteLine("Other Error: {0}", e.Message);
        }
        
        Console.ReadKey();
    }
}

ผลลัพธ์

Custom Exception: Zero Temperature found
Temp Value: 0

Best Practices

  • ชื่อลงท้ายด้วย Exception (e.g., InsufficientFundsException)
  • 繼承 Exception (ไม่ใช่ ApplicationException - Legacy)
  • ให้ Constructor อย่างน้อย 3 ตัว: Default, Message, Message+Inner
  • ทำให้ Serializable (สำหรับ Distributed Systems)
  • Override ToString() ถ้าต้องการ Format พิเศษ

เมื่อไหร่ควรสร้าง Custom Exception

  • Business Rule Violation (InsufficientFunds, InvalidState)
  • ต้องการข้อมูลเพิ่มเติม (Error Codes, Entity IDs)
  • Caller ต้อง Handle แยกจาก Exception อื่นๆ