2.7. Making Python Programs Robust

2.7.1. Exceptions

Here is a super cautious, but correct way to open and read a file:

import sys

try:
    file = open('myFile')
except IOError:
    print 'File does not exist.'
    sys.exit(1)
else:
    print 'File exists.'

try:
    lines = file.readlines()
finally:
    file.close()
  • The else block executes only if no exceptions are thrown, while the finally block always executes. The file.close() statement is in a finally block to ensure that it gets closed, even if an uncaught exception is raised and the program will exit.

Following is the new, cleaner, but just as robust way to express the same operation in Python. This works because the file object was made to work with the new with keyword to ensure that the file is always closed after being opened. [1]

try:
    with open('myFile') as file:
        lines = file.readlines()
except IOError:
    print 'File does not exist.'
    sys.exit(1)
else:
    print 'File exists and has been read.'

Footnotes

[1]The with statement is a newer feature in Python. It works with some objects to make the syntax of handling the object in a robust manner much cleaner. The with keyword also works with the socket object, which is of prime interest to us in this class. However, it was introduced after our text book was written.

Table Of Contents

Previous topic

2.6. Organizing Python Source Code

Next topic

2.8. Python’s Built-in Functions and Standard Library

This Page