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