Why no try-except-finally ?

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Nov 5 04:56:24 EST 2003
keflimarcusx at aol.comNOSPAM (KefX) wrote in
news:20031105044006.29195.00000177 at mb-m22.aol.com: 

> I bring this up because I originally wrote this in my game code:
> 
> try:
>     PlayGame()
> except:
>     err_msg = "FATAL ERROR: " + sys.exc_info()[0]
>     logger.critical(err_msg)
> finally:
>     DeInit()
> 
> In other words, if something went wrong, an error message would be
> printed out to the log, and then in either case, my game would try to
> exit gracefully. Of course, rewriting it without the finally: is no
> big deal (just write DeInit() in the except block and again after the
> block)...in this case. What if I wanted to execute a bunch of lines?
> Code duplication is bad. 

Hang on, there is something wrong with what you say here. If you really had 
the code you wrote above, and you put DeInit() in the except block and 
again after it then any time an exception was thrown you would call DeInit 
twice. Is this *really* what you wanted?

This code would reliably call DeInit every time, whether or not an 
exception was thrown, without code duplication:

try:
    PlayGame()
except:
    err_msg = "FATAL ERROR: " + sys.exc_info()[0]
    logger.critical(err_msg)
DeInit()

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