हम पायथन में एक नई एक्सेप्शन क्लास बनाकर यूजर-डिफाइंड या कस्टम एक्सेप्शन बनाते हैं। विचार कस्टम एक्सेप्शन क्लास को एक्सेप्शन क्लास से प्राप्त करना है। अधिकांश बिल्ट-इन एक्सेप्शन अपने एक्सेप्शन को लागू करने के लिए उसी विचार का उपयोग करते हैं।
दिए गए कोड में, आपने एक यूजर-डिफाइंड एक्सेप्शन क्लास बनाई है, "CustomException"। यह पैरेंट के रूप में Exception क्लास का उपयोग कर रहा है। इसलिए, नई यूजर-डिफाइंड एक्सेप्शन क्लास किसी अन्य एक्सेप्शन क्लास की तरह एक्सेप्शन उठाएगी यानी वैकल्पिक एरर मैसेज के साथ "raise" स्टेटमेंट को कॉल करके।
आइए एक उदाहरण लेते हैं।
इस उदाहरण में, हम दिखाते हैं कि यूजर-डिफाइंड एक्सेप्शन कैसे उठाएं और प्रोग्राम में एरर्स कैसे पकड़ें। साथ ही, नमूना कोड में, हम यूजर से बार-बार एक अल्फाबेट दर्ज करने के लिए कहते हैं जब तक कि वह केवल स्टोर किया गया अल्फाबेट दर्ज नहीं करता।
मदद के लिए, प्रोग्राम यूजर को एक संकेत प्रदान करता है ताकि वह सही अल्फाबेट का पता लगा सके।
# Python user-defined exceptions
class CustomException(Exception):
"""Base class for other exceptions"""
pass
class PrecedingLetterError(CustomException):
"""Raised when the entered alphabet is smaller than the actual one"""
pass
class SucceedingLetterError(CustomException):
"""Raised when the entered alphabet is larger than the actual one"""
pass
# हमें इस अल्फाबेट को तब तक अनुमान लगाना है जब तक हम इसे सही नहीं कर लेते
alphabet = 'k'
while True:
try:
foo = raw_input("Enter an alphabet: ")
if foo < alphabet:
raise PrecedingLetterError
elif foo > alphabet:
raise SucceedingLetterError
break
except PrecedingLetterError:
print("The entered alphabet is preceding one, try again!")
print('')
except SucceedingLetterError:
print("The entered alphabet is succeeding one, try again!")
print('')
print("Congratulations! You guessed it correctly.")