Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Luồng điều khiển try catch finally trong C#

Ví dụ chia số, xử lý DivideByZeroException.

Ví dụ

using System;

namespace ErrorHandlingApplication
{
    class DivNumbers
    {
        int result;
        
        public void Division(int num1, int num2)
        {
            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
            }
            finally
            {
                Console.WriteLine("Result: {0}", result);
            }
        }
        
        static void Main(string[] args)
        {
            DivNumbers d = new DivNumbers();
            d.Division(25, 0);
            Console.ReadKey();
        }
    }
}

Kết quả

Exception: Attempted to divide by zero.
Result: 0

Flow Control

  1. Exception trong try -> nhảy đến catch phù hợp
  2. Catch xong -> chạy finally
  3. Không exception -> try xong -> chạy finally
  4. Return trong try/catch -> finally vẫn chạy trước khi return
  5. Exception không catch -> finally chạy -> propagate lên caller

Best Practices

  • Catch specific exception trước, general sau
  • Không catch Exception chung trừ top-level
  • Dùng using / IDisposable cho resource cleanup (tự gọi Dispose trong finally)
  • throw; preserve stack trace, throw ex; reset stack trace