finally Block ใช้สำหรับโค้ดที่ต้องรัน ทุกครั้ง ไม่ว่าจะมี Exception หรือไม่ก็ตาม (Cleanup Code)
โครงสร้าง Try-Catch-Finally
try
{
// โค้ดที่อาจเกิด Exception
}
catch (ExceptionType ex)
{
// จัดการ Exception
}
finally
{
// รันเสมอ - ปิดไฟล์, ปิด Connection, Cleanup
}
ตัวอย่าง: ปิดไฟล์ใน finally
using System;
using System.IO;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
public void Division(int num1, int num2)
{
FileStream fs = null;
try
{
fs = new FileStream("log.txt", FileMode.Append);
result = num1 / num2; // อาจ DivideByZeroException
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e.Message);
}
finally
{
// ปิดไฟล์เสมอ แม้จะมี Exception
if (fs != null)
{
fs.Close();
Console.WriteLine("File closed in finally block");
}
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.Division(25, 0);
Console.ReadKey();
}
}
}
ลำดับการทำงาน
- รัน
tryBlock - ถ้าไม่มี Exception → ข้าม
catch→ รันfinally - ถ้ามี Exception → รัน
catchที่ตรง → รันfinally - ถ้ามี Exception ไม่มี
catchตรง → รันfinally→ โยน Exception ต่อ
Using Statement (Best Practice สำหรับ IDisposable)
using (FileStream fs = new FileStream("log.txt", FileMode.Append))
{
// ใช้ fs
} // fs.Dispose() เรียกอัตโนมัติ (เหมือน finally)
ข้อควรระวัง
finallyไม่รันถ้า:Environment.FailFast(), Process Killed, Stack Overflow- อย่า
returnในfinally(ซ่อน Exception) - อย่าโยน Exception ใหม่ใน
finally(ทับ Exception เดิม)