जावा थ्रो कीवर्ड
उदाहरण
यदि आयु 18 वर्ष से कम है तो अपवाद फेंक दें (प्रिंट "प्रवेश निषेध")। यदि आयु 18 वर्ष या अधिक है, तो "प्रवेश प्रदान किया गया" प्रिंट करें:
public class Main {
static void checkAge(int age) {
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...)
}
}
परिभाषा और उपयोग
कीवर्ड का throw
उपयोग कस्टम त्रुटि बनाने के लिए किया जाता है।
कथन का उपयोग अपवाद प्रकारthrow
के साथ किया जाता है । जावा में कई अपवाद प्रकार उपलब्ध हैं: , , , , आदि।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 में अपवादों के बारे में और पढ़ें ।