पाठ 31 / 49
एक्सेप्शन उठाना और कस्टम एक्सेप्शन
गलत input को जल्दी reject करने के लिए exceptions raise करें, और अपने domain के लिए custom exception classes बनाएँ।
raise
raise मैन्युअल रूप से एक्सेप्शन ट्रिगर करता है — अमान्य इनपुट को जल्द से जल्द अस्वीकार करने के लिए उपयोगी।
def set_age(age):
if age < 0:
raise ValueError("age can't be negative")
return age
set_age(-5) # raises ValueError: age can't be negativeकस्टम एक्सेप्शन क्लास
अपना डोमेन-विशिष्ट एरर बनाने के लिए Exception का उपवर्ग बनाएँ, जिसे आपका कोड — और कॉल करने वाले — नाम से पकड़ सकें।
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("not enough balance")
return balance - amount
try:
withdraw(100, 500)
except InsufficientFundsError as e:
print("Blocked:", e)