Python except शब्द
उदाहरण
यदि वाक्यांश त्रुटि उठाता है, तो "कुछ गलती हुई" प्रिंट करें:
try: x > 3 except: print("कुछ गलती हुई")
डिफाइन और उपयोग
try ... except ब्लॉक में except शब्द का उपयोग किया गया है। यह त्रुटि को उठाने के बाद चलने वाले कोड ब्लॉक को डिफाइन करता है。
आप विभिन्न त्रुटि प्रकारों के लिए विभिन्न ब्लॉक डिफाइन कर सकते हैं, और ना क्या त्रुटि होने के समय चलने वाले ब्लॉक, नीचे के उदाहरण को देखें。
More instances
Instance 1
If NameError is raised, write a message, and if TypeError is raised, write another one:
x = "hello" try: x > 3 except NameError: print("You have a variable that is not defined.") except TypeError: print("You are comparing values of different type")
Instance 2
Attempt to execute a statement that raises an error, but do not define an error type (in this case ZeroDivisionError):
try: x = 1/0 except NameError: print("You have a variable that is not defined.") except TypeError: print("You are comparing values of different type") except: print("Something else went wrong")
Instance 3
If no error occurs, write a message:
x = 1 try: x > 10 except NameError: print("You have a variable that is not defined.") except TypeError: print("You are comparing values of different type") else: print("The 'Try' code was executed without raising any errors!")