कीवर्ड को छोड़कर पायथन
उदाहरण
यदि कथन एक त्रुटि प्रिंट उठाता है "कुछ गलत हो गया":
try:
x > 3
except:
print("Something went wrong")
परिभाषा और उपयोग
कीवर्ड का except
प्रयोग try... ब्लॉक को छोड़कर में किया जाता है। यह कोड के एक ब्लॉक को चलाने के लिए परिभाषित करता है यदि कोशिश ब्लॉक एक त्रुटि उठाता है।
आप विभिन्न त्रुटि प्रकारों के लिए अलग-अलग ब्लॉक को परिभाषित कर सकते हैं, और कुछ भी गलत नहीं होने पर निष्पादित करने के लिए ब्लॉक, नीचे उदाहरण देखें।
और ज्यादा उदाहरण
उदाहरण
एक संदेश लिखें यदि यह एक NameError है, और दूसरा यदि यह एक TypeError है:
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")
उदाहरण
एक कथन निष्पादित करने का प्रयास करें जो त्रुटि उत्पन्न करता है, लेकिन परिभाषित त्रुटि प्रकारों में से कोई भी नहीं (इस मामले में, एक 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")
उदाहरण
कोई त्रुटि न होने पर संदेश लिखें:
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!")
संबंधित पृष्ठ
try
कीवर्ड ।
finally
कीवर्ड ।