First page Back Continue Last page Overview Graphics

The optional else Clause

The try-except statement can have an optional else clause.

If it is present, it must follow all except clauses.

It is useful for code that must be executed, if the try clause does not raise an exception.

arg = "yellow_snow.txt"

try:

f = open(arg, 'r')

except IOError:

print('cannot open', arg)

else:

print(arg, 'has', len(f.readlines()), 'lines')

f.close()