जावा कीवर्ड फेंकता है
उदाहरण
यदि आयु 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
किसी विधि द्वारा किस अपवाद प्रकार को फेंका जा सकता है।
जावा में कई अपवाद प्रकार उपलब्ध हैं: 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 में अपवादों के बारे में और पढ़ें ।