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

Finally Statement ใน C# คืออะไร

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();
        }
    }
}

ลำดับการทำงาน

  1. รัน try Block
  2. ถ้าไม่มี Exception → ข้าม catch → รัน finally
  3. ถ้ามี Exception → รัน catch ที่ตรง → รัน finally
  4. ถ้ามี 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 เดิม)