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

Flow Control ใน Try Catch Finally ใน C#

ทำความเข้าใจ Flow Control ด้วยตัวอย่างหารเลข:

ตัวอย่าง

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

ผลลัพธ์

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

Flow Control:

  • เกิด Exception ใน try -> ไป catch block
  • หลัง catch เสร็จ -> ไป finally block
  • ไม่มี Exception -> try ทำงานเสร็จ -> ไป finally block