استثناءات مخصصة
تعريف استثناءات مخصصة استثناءات مخصصة
يمكنك إنشاء أنواع استثناءات خاصة بموضوع مشروعك لوضوح رسائل الخطأ.
إنشاء صنف يرث من Exception (لـ checked) أو RuntimeException (لـ unchecked) يتيح رسائل خطأ مخصصة. مفيد في المشاركب الكبيرة لتمييز أنواع الأخطاء.
الصياغة
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("رصيد غير كافٍ: " + amount);
this.amount = amount;
}
}📄 مثال
public class InsufficientFundsException extends RuntimeException {
private double deficit;
public InsufficientFundsException(double deficit) {
super("المبلغ المطلوب: " + deficit);
this.deficit = deficit;
}
public double getDeficit() { return deficit; }
}
void withdraw(double amount) {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
}أهم النقاط
| العنصر | الوظيفة |
|---|---|
| extends Exception | checked exception — يجب التعامل معها إجباريًا |
| extends RuntimeException | unchecked exception — اختيارية |
| getMessage() | رسالة الخطأ |
| getCause() | الاستثناء الأصل الذي تسبب في هذا |
💡 نصائح عملية
- اسم الصنف يجب أن ينتهي بـ Exception: PaymentFailedException
- أضف حقول مفيدة (مثل getDeficit()) لتسهيل معالجة الخطأ
⚠️ أخطاء شائعة
- nxing extends Exception للاستخدام العام —unchecked (RuntimeException) أبسط لمعظم الحالات
- عدم تضمين رسالة واضحة في constructor — تُصعّب التتبع
خصائص ذات صلة
🎓 تريد فهم الصورة الكاملة خطوة بخطوة؟ ابدأ من مسار JAVA الكامل بالعربي.