Why no try-except-finally ?

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Nov 5 04:56:25 EST 2003


keflimarcusx at aol.comNOSPAM (KefX) wrote in
news:20031105040556.29079.00000209 at mb-m22.aol.com: 

> This may have been discussed before, but I'm kind of confused as to
> why Python doesn't support having both an except ~and~ a finally
> clause, like this: 
> 
> try:
>     raise RuntimeException
> except:
>     print "What is the answer?"
> finally:
>     print 42
> 
> This doesn't work because I use both 'except' and 'finally'. I'm not
> saying that it SHOULD work, I'm wondering why it doesn't. 

The first thing to ask yourself when wondering why something doesn't work 
in Python, is exactly what you expect it should do.

The 'try' block can exit normally; by throwing an exception that is caught 
by an 'except'; or by throwing an exception that is not caught and 
propogates outside. Do you want the 'finally' block executed in all of 
those cases, or only for some of them?


The answer to your question, given by Tim Peters in
http://groups.google.com/groups?selm=LNBBLJKPBEHFEDALKOLCMEONGIAA.tim_one%4
0email.msn.com
is that Python used to allow this, and people got caught out because it 
didn't work the way everyone expected. By writing try/except/else and 
try/finally separately you can clearly communicate what you expect to 
happen.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list