Python Custom Exceptions
In this page:
class CustomError(Exception):
pass
raise CustomError("message")
Custom Exception बनाना
built-in Exception class से inherit करने वाली नई class define करना एक custom exception type बनाता है -- एक खाली 'class InsufficientFundsError(Exception): pass' भी raise और except के साथ तुरंत उपयोग करने योग्य होता है, जो आपके errors को आपके application के domain के अनुसार एक specific नाम देता है।
उदाहरण: Creating a Custom Exception
class InsufficientFundsError(Exception): # custom exception type
pass
try:
raise InsufficientFundsError()
except InsufficientFundsError:
print("Custom exception caught")
Custom Messages जोड़ना
__init__ को override करके एक message स्वीकार करना और उसे super().__init__(message) के ज़रिए parent class को पास करना आपके custom exception को built-in exceptions की तरह ही एक description ले जाने देता है, ताकि str(my_exception) खाली रहने की बजाय कुछ अर्थपूर्ण लौटाए।
उदाहरण: Adding Custom Messages
class InsufficientFundsError(Exception):
def __init__(self, message):
super().__init__(message) # passes the message to the base Exception
try:
raise InsufficientFundsError("balance too low")
except InsufficientFundsError as e:
print(str(e))
Custom Exceptions Raise करना
आप custom exception को उसी तरह trigger करते हैं जैसे किसी built-in को -- raise InsufficientFundsError('balance too low') -- जो तुरंत सामान्य execution रोक देता है और call stack में ऊपर एक matching except block ढूँढता है।
उदाहरण: Raising Custom Exceptions
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("balance too low") # triggers the custom exception
try:
withdraw(100, 200)
except InsufficientFundsError as e:
print(e)
Custom Exceptions Catch करना
Custom exception catch करना बिल्कुल built-in catch करने जैसा ही काम करता है: 'except InsufficientFundsError as e:' -- यह calling code को generic conditions की बजाय आपके application की अपनी error conditions पर specific रूप से प्रतिक्रिया देने देता है।
उदाहरण: Catching Custom Exceptions
class InsufficientFundsError(Exception):
pass
try:
raise InsufficientFundsError("Not enough money")
except InsufficientFundsError as e: # catches the custom type like any built-in one
print("Caught:", e)
Custom Attributes जोड़ना
message के अलावा, आप __init__ में custom exception से extra attributes जोड़ सकते हैं (जैसे self.error_code = code), जिससे उसे catch करने वाले except blocks सिर्फ़ human-readable string की बजाय ठीक क्या गलत हुआ उसकी structured details तक पहुँच पाते हैं।
उदाहरण: Adding Custom Attributes
class InsufficientFundsError(Exception):
def __init__(self, message, error_code):
super().__init__(message)
self.error_code = error_code # extra structured detail beyond the message
try:
raise InsufficientFundsError("balance too low", 402)
except InsufficientFundsError as e:
print(e, e.error_code)
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: