The else Clause

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 :

suite else:


The percentage is 1.0 The percentage is 1.0 Traceback (innermost last): File "<stdin>", line 1, in ? File "C:\\.\", line 19, in ? File "C:\\.\", line 4, in figurePercentage AttributeError: _getitem_

Using our denominator example (, 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[0] denominator = tuple[1] percent = numerator/denominator percent = percent * 100

print ("The percentage is " + "percent" + "%") except ZeroDivisionError:

print ("divide by 0 percentage error")

except :

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?

0 0

Post a comment