Newbie question about exceptions
Vijay Baliga
vijaybaliga at hotmail.com
Thu Feb 24 15:39:57 EST 2000
Thanks for your help, Remco! My news server was down, and I only saw your
post today. What would I do if I sometimes wanted to "return" from within
the try: block? If gotos were allowed, I could do something like this:
goto Cleanup
...
Cleanup:
f1.close()
Or, if I could have "finally" with "try/except", then I could simply
"return", and be sure that the "finally" clause would be executed on the way
out.
Thanks,
Vijay
"Remco Gerlich" <scarblac-spamtrap at pino.selwerd.nl> wrote in message
news:slrn8b3pvt.6ij.scarblac-spamtrap at flits104-37.flits.rug.nl...
> 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