I have the following code (adapted from an example given in Dive Into Python) that reads the entire contents of a file into a buffer.
buffer = ""
try:
file = open(postFileName, 'rU')
try:
# Read the entire POST log file into a buffer
buffer += file.read()
finally:
file.close()
except IOError:
buffer += "The POST file could not be opened."
What's bothering me about this code is the inner try/finally block without an except block. Do I need an except block in there? Can the call to read()
fail after the call to open()
was successful? I know the try-except-finally is now unified, so adding one, at least syntactically, is not a problem.
If I add an except block, under what conditions will it be executed, and how do I write a test to make sure it runs under those conditions?
Additionally, if I don't need an except block, then why do I need the inner try/finally block at all?