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

Try-Catch-Finally ใน C# (การจัดการข้อยกเว้น)

C# Exception Handling ใช้ Keywords: try, catch, finally

  • try - บล็อกที่อาจเกิด Exception
  • catch - จับและจัดการ Exception
  • finally - รันเสมอ ไม่ว่าจะมี Exception หรือไม่

ตัวอย่าง: การหารด้วยศูนย์

using System;

namespace ErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        DivNumbers() { result = 0; }

        public void division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception caught: {0}", e);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }
        }

        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.division(25, 0);
            Console.ReadKey();
        }
    }
}

Output

Exception caught: System.DivideByZeroException: Attempted to divide by zero.
Result: 0