يلقي جافا الكلمات الرئيسية
مثال
قم بطرح استثناء إذا كان العمر أقل من 18 عامًا (اطبع "تم رفض الوصول"). إذا كان عمرك 18 عامًا أو أكثر ، فقم بطباعة "تم منح حق الوصول":
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
التعريف والاستخدام
تشير throws
الكلمة الأساسية إلى نوع الاستثناء الذي قد يتم طرحه بواسطة طريقة ما.
هناك العديد من أنواع الاستثناءات المتوفرة في Java: ArithmeticException
، ClassNotFoundException
، ArrayIndexOutOfBoundsException
، SecurityException
، إلخ.
الاختلافات بين throw
و throws
:
throw | throws |
---|---|
Used to throw an exception for a method | Used to indicate what exception type may be thrown by a method |
Cannot throw multiple exceptions | Can declare multiple exceptions |
Syntax:
|
Syntax:
|
الصفحات ذات الصلة
اقرأ المزيد حول الاستثناءات في برنامج Java Try..Catch Tutorial .