Skip to content
scipython.com

Q4.1.1The else block of a try ... except clause

What is the point of else? Why not put statements in this block inside the original try block?

Show solution

It is a good idea to keep the try block as small as possible to prevent exceptions that you do not want to catch being caught instead of the one you do. For example, in Example E4.5, suppose we read the file after opening it within the sametry block:

try:
    fi = open(filename, 'r')
    lines = fi.readlines()
except IOError:
    ...

Now there are two errors that could give rise to an IOError exception being raised: failure to open the file and failure to read its lines. The except clause is intended to handle the first case, but it will also be executed in the second case when it would be more appropriate to handle it differently (or leave it unhandled and stop program execution).