पाठ 30 / 47
एक्सेप्शन उठाना और कस्टम एक्सेप्शन
जान-बूझकर त्रुटि का संकेत दें, और अपने खुद के एक्सेप्शन प्रकार बनाएँ।
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)