我有下面这段代码(改编自Dive Into Python中的一个例子),它将文件的全部内容读入缓冲区。
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."
这段代码让我感到困扰的是内部try/finally块没有except块。我需要在这里加一个except块吗?调用
read()
函数是否可能在调用open()
成功后失败?我知道现在try-except-finally已经统一了,所以至少从语法上添加一个except块不是问题。如果我添加一个except块,在什么条件下它会被执行,如何编写测试来确保在这些条件下运行?
此外,如果我不需要except块,那么为什么需要内部try/finally块呢?