مدیریت خطاها (Exceptions) در C#

Exception ها مکانیزمی در C# هستند که برای مدیریت خطاهای زمان اجرا استفاده می‌شوند و باعث جلوگیری از crash شدن برنامه می‌شوند.

Exception چیست؟

Exception یک خطای زمان اجرا است که باعث توقف جریان طبیعی برنامه می‌شود و باید به‌درستی مدیریت شود.

try / catch


try
{
    int a = 10;
    int b = 0;

    int result = a / b;

    Console.WriteLine(result);
}
catch (Exception ex)
{
    Console.WriteLine("Error occurred: " + ex.Message);
}

finally

بلاک finally همیشه اجرا می‌شود، چه خطا رخ بدهد چه ندهد.


try
{
    Console.WriteLine("Doing work...");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    Console.WriteLine("Cleanup resources");
}

catch های چندگانه


try
{
    int[] arr = new int[2];
    Console.WriteLine(arr[5]);
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Index error");
}
catch (Exception ex)
{
    Console.WriteLine("General error");
}

throw کردن Exception


public void Divide(int a, int b)
{
    if (b == 0)
        throw new DivideByZeroException("b cannot be zero");

    Console.WriteLine(a / b);
}

Custom Exception


public class InvalidAgeException : Exception
{
    public InvalidAgeException(string message) : base(message)
    {
    }
}

public void RegisterUser(int age)
{
    if (age < 18)
        throw new InvalidAgeException("Age must be at least 18");
}

Best Practices

  • فقط در شرایط غیرقابل پیش‌بینی از Exception استفاده کن
  • از catch عمومی زیاد استفاده نکن
  • Exception ها را لاگ کن
  • از throw کردن خطای خام جلوگیری کن

کاربرد در پروژه واقعی


try
{
    _repository.Add(entity);
}
catch (Exception ex)
{
    _logger.LogError(ex, "Error while adding entity");
    throw;
}

جمع‌بندی

Exception handling یکی از بخش‌های مهم در نوشتن برنامه‌های پایدار و قابل اعتماد در C# است و به ما کمک می‌کند کنترل خطاها را در دست بگیریم.