#️⃣ شرح C#

معالجة الاستثناءات

try / catch

try
{
    int result = 10 / int.Parse("0");
}
catch (DivideByZeroException)
{
    Console.WriteLine("لا يمكن القسمة على صفر");
}

التقاط الرسالة

try { /* ... */ }
catch (Exception ex)
{
    Console.WriteLine($"خطأ: {ex.Message}");
}

عدّة catch

try { /* ... */ }
catch (FormatException) { Console.WriteLine("تنسيق خاطئ"); }
catch (OverflowException) { Console.WriteLine("تجاوز"); }
catch (Exception) { Console.WriteLine("خطأ آخر"); }

finally

ينفّذ دائمًا — لتحرير الموارد:

try { /* ... */ }
catch (Exception) { /* ... */ }
finally { Console.WriteLine("تنظيف"); }

رمي استثناء

void SetAge(int age)
{
    if (age < 0)
        throw new ArgumentException("العمر سالب");
}

استثناء مخصّص

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

💡 التقط الاستثناءات المحدّدة قبل العامّة، ولا تبتلع الأخطاء بـ catch فارغ.

🎯 التالي: التعامل مع الملفات.