Why no try-except-finally ?

KefX keflimarcusx at aol.comNOSPAM
Wed Nov 5 04:40:06 EST 2003


>The separation is probably because the purpose of try..finally is different
>from exception handling and mixing the two would obscure that (or maybe
>there is some wizardry under the hood).

I dunno. Other languages such as Java support "try-catch-finally" (or
"try-except-finally" as we're calling it), and I don't see how the lack of
restrictions does anything bad like, say, reduce the clarity of code.

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. Well, I could write a
local function and just have it call THAT in both cases, but that felt like
overkill. Thus, I came up with the 'nested-try idiom':

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

But it looks kind of ugly. But it's still easy to just change the statements in
the 'finally' block if needed. But the nested-try looks strange, and worse, you
have to remember to put the 'raise' in the except block (remember I forgot to
do this in my original post!), and error-handling code tends to be the
least-tested...

I dunno. More thoughts?

- Kef





More information about the Python-list mailing list