Another feature of the first form of the try statement is the else clause. else's suite is executed only if no exceptions occurred.
suite except expression-target: s uite except :
The percentage is 1.0 The percentage is 1.0 Traceback (innermost last): File "<stdin>", line 1, in ? File "C:\\.\divby0_2.py", line 19, in ? File "C:\\.\divby0_2.py", line 4, in figurePercentage AttributeError: _getitem_
Using our denominator example (divby0_4.py), if we want to determine if any exceptions occurred, we can add anelse clause to the end of our try st atemeni as follows:
def figurePercentage(figures): for tuple in figures: try :
numerator = tuple denominator = tuple percent = numerator/denominator percent = percent * 100
print ("The percentage is " + "percent" + "%") except ZeroDivisionError:
print ("divide by 0 percentage error")
print ("percentage error")
print ("No exceptions occurred")
If br exceptions occurred, the figurePercentage () function prints out "No exceptions occurred " during each iteration in which that statement remains true.
Was this article helpful?