हर प्रोग्रामिंग भाषा में प्रोग्राम निष्पादन के दौरान उत्पन्न अपवादों को संभालने की सुविधा होती है। Python में assert कीवर्ड का उपयोग त्रुटि को पकड़ने और सिस्टम-जनित त्रुटि संदेश के बजाय उपयोगकर्ता-परिभाषित त्रुटि संदेश दिखाने के लिए किया जाता है। इससे प्रोग्रामर के लिए त्रुटि का पता लगाना और उसे ठीक करना आसान हो जाता है।
Assert के साथ
नीचे दिए गए उदाहरण में हम assert कीवर्ड का उपयोग शून्य से विभाजन त्रुटि को पकड़ने के लिए करते हैं। संदेश प्रोग्रामर की इच्छा के अनुसार लिखा जाता है।
उदाहरण
x = 4
y = 0
assert y != 0, "if you divide by 0 it gives error"
print("Given values are ", "x:", x, "y:", y)
print("\nmultiplication of x and y is", x * y)
print("\ndivision of x and y is", x / y)
उपरोक्त कोड चलाने पर निम्न परिणाम मिलता है:
Traceback (most recent call last):
File "scratch.py", line 3, in
assert y != 0, "if you divide by 0 it gives error"
AssertionError: if you divide by 0 it gives error
Assert के बिना
assert स्टेटमेंट के बिना हमें सिस्टम-जनित त्रुटियाँ मिलती हैं जिन्हें समझने और त्रुटि के स्रोत का पता लगाने के लिए आगे जांच की आवश्यकता हो सकती है।
उदाहरण
x = 4
y = 0
#assert y != 0, "if you divide by 0 it gives error"
print("Given values are ", "x:", x, "y:", y)
print("\nmultiplication of x and y is", x * y)
print("\ndivision of x and y is", x / y)
उपरोक्त कोड चलाने पर निम्न परिणाम मिलता है:
multiplication of x and y is 0 Traceback (most recent call last): File "scratch.py", line 6, inprint("\ndivision of x and y is", x / y) ZeroDivisionError: division by zero