Newbie question about exceptions
Vijay Baliga
vijaybaliga at hotmail.com
Mon Feb 21 14:17:50 EST 2000
Why isn't "finally" allowed with "try/except"? Ideally, I would like to do
the following:
try:
f1 = open(file1)
use(f1)
f2 = open(file2)
use(f1, f2)
f3 = open(file3)
use(f1, f2, f3)
except:
print 'File open error'
finally:
f1.close()
f2.close()
f3.close()
So the file handles are always closed, even if an exception occurs while
opening the files. The only solution that I can think of is:
try:
try:
f1 = open(file1)
use(f1)
f2 = open(file2)
use(f1, f2)
f3 = open(file3)
use(f1, f2, f3)
finally:
f1.close()
f2.close()
f3.close()
except:
print 'File open error'
However, I don't like it because it is more verbose and everything is
indented an additional tab stop.
Thanks in advance for any help,
Vijay
vijaybaliga at hotmail.com
More information about the Python-list
mailing list