Newbie question about exceptions

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Mon Feb 21 20:41:02 EST 2000


Vijay Baliga wrote in comp.lang.python:
> Why isn't "finally" allowed with "try/except"?

Everything with "except:" is done if that exception is matched. A
"finally:" clause is executed regardless of whether an exception
was raised. If you have an "except:" clause already, that's quite
superfluous.

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()

How about:

try:
    f1 = open(file1)
	(etc)
except: 
    print 'File open error'
f1.close()

It will always get there.

(Of course, no need to close files - it'll be done automatically after the
file leaves scope, because of refcounting)



-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
"Early to rise, early to bed, makes a man healthy, wealthy and dead." -- TP



More information about the Python-list mailing list