कभी-कभी एप्लिकेशन की आवश्यकताओं के आधार पर सार्थक अपवाद विकसित करना आवश्यक होता है। Java में हम Exception क्लास को एक्सटेंड करके अपने खुद के अपवाद (Custom Exceptions) बना सकते हैं।
उपयोगकर्ता-परिभाषित अपवादों को Java में कस्टम अपवाद (Custom Exceptions) के नाम से भी जाना जाता है।
कस्टम अपवाद बनाने के चरण (उदाहरण सहित)
- CustomException क्लास बनाएं जो
Exceptionक्लास को एक्सटेंड करे। - अपवाद संदेश को स्थानीय रूप से स्टोर करने के लिए एक लोकल वेरिएबल
messageबनाएं। - कस्टम अपवाद ऑब्जेक्ट के कंस्ट्रक्टर में एक स्ट्रिंग आर्गुमेंट पास करें। कंस्ट्रक्टर उस आर्गुमेंट स्ट्रिंग को प्राइवेट
messageवेरिएबल में सेट करे। toString()मेथड को ओवरराइड करें ताकि अपवाद संदेश प्रिंट हो सके।mainमेथड मेंtry-catchब्लॉक का उपयोग करके कस्टम अपवाद को फेंकें (throw) और देखें कि कस्टम अपवाद बनाते समय स्ट्रिंग कैसे पास की जाती है।catchब्लॉक में संदेश प्रिंट करें।
उदाहरण
class CustomException extends Exception {
String message;
CustomException(String str) {
message = str;
}
@Override
public String toString() {
return ("Custom Exception Occurred : " + message);
}
}
public class MainException {
public static void main(String args[]) {
try {
throw new CustomException("This is a custom message");
} catch (CustomException e) {
System.out.println(e);
}
}
}
आउटपुट
Custom Exception Occurred : This is a custom message
सर्वोत्तम अभ्यास (Best Practices)
- Checked vs Unchecked: अगर आप चाहते हैं कि कॉलर अनिवार्य रूप से अपवाद को हैंडल करे, तो
Exceptionएक्सटेंड करें (Checked)। अगर रनटाइम अपवाद चाहते हैं, तोRuntimeExceptionएक्सटेंड करें (Unchecked)। - सीरियलाइजेशन:
serialVersionUIDडिक्लेयर करें। - कंस्ट्रक्टर्स: सभी मानक कंस्ट्रक्टर्स प्रदान करें (नो-आर्ग, मैसेज के साथ, कारण के साथ, मैसेज और कारण दोनों के साथ)।
- नामकरण: क्लास का नाम
Exceptionसे समाप्त होना चाहिए (जैसेInsufficientFundsException)।
उन्नत उदाहरण (Best Practices के साथ)
public class InsufficientFundsException extends Exception {
private static final long serialVersionUID = 1L;
private double amount;
public InsufficientFundsException(String message) {
super(message);
}
public InsufficientFundsException(String message, Throwable cause) {
super(message, cause);
}
public InsufficientFundsException(double amount) {
super("Insufficient funds. Required: " + amount);
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
निष्कर्ष: कस्टम अपवाद एप्लिकेशन-विशिष्ट त्रुटियों को स्पष्ट रूप से व्यक्त करने में मदद करते हैं और कोड को अधिक पठनीय और रखरखाव योग्य बनाते हैं।