Python में try/except से Error Handling
Exceptions सामान्य execution path को invalid input और failed operations से अलग रखते हैं।
में try/except से Error Handling क्या है?
Exceptions सामान्य execution path को invalid input और failed operations से अलग रखते हैं।
अपेक्षित errors को स्पष्ट रूप से संभालें।
इसका उपयोग कब करें?
- चलने योग्य code से Python syntax सीखें।
- बड़ी programming समस्याओं से पहले मजबूत आधार बनाएँ।
- स्थानीय setup के बिना किसी विचार को तुरंत जाँचें।
उदाहरण कोड
main.py
value = "not-a-number"
try:
number = int(value)
print(number)
except ValueError:
print("Please provide a valid integer")
finally:
print("Conversion finished")
अपेक्षित आउटपुट
Please provide a valid integer
Conversion finished
यह कैसे काम करता है
try में risky operation होता है; except को specific exception पकड़ना चाहिए ताकि अनपेक्षित bugs न छिपें।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- Code चलाने से पहले output का अनुमान लगाएँ।
- खाली और गलत input संभालें।
- Logic को function में रखें और tests जोड़ें।