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

Exception Handling ใน C# คืออะไร

Exception Handling จัดการข้อผิดพลาด Runtime โดยใช้ 4 Keywords:

Keywordหน้าที่
tryบล็อกโค้ดที่อาจเกิด Exception
catchจับและจัดการ Exception
finallyรันเสมอ (Cleanup)
throwโยน Exception เอง

ตัวอย่างพื้นฐาน

using System;

namespace MyErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        
        public void MyDivision(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception Caught: {0}", e.Message);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }
        }
        
        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.MyDivision(5, 0);
            Console.ReadKey();
        }
    }
}

หลาย Catch Blocks (เรียงจาก Specific ไป General)

try
{
    // risky code
}
catch (FileNotFoundException ex)
{
    // Handle file not found
}
catch (IOException ex)
{
    // Handle IO errors
}
catch (Exception ex)
{
    // Handle all other exceptions
}
finally
{
    // Cleanup
}

Throw Exception เอง

if (age < 0)
    throw new ArgumentException("Age cannot be negative", nameof(age));

Exception Hierarchy (สำคัญ)

System.Object
└── System.Exception
    ├── System.SystemException (Runtime Errors)
    │   ├── NullReferenceException
    │   ├── IndexOutOfRangeException
    │   ├── DivideByZeroException
    │   └── InvalidOperationException
    └── System.ApplicationException (Custom Exceptions - Legacy)
        └── YourCustomException

Best Practices

  • Catch Specific Exceptions ก่อน General
  • อย่า Catch Exception แล้วทิ้งว่าง (Swallow)
  • ใช้ throw; (ไม่ใช่ throw ex;) เพื่อ Preserve Stack Trace
  • ใช้ using / try-finally สำหรับ Resource Cleanup
  • สร้าง Custom Exception สำหรับ Business Logic Errors