[Python-3000] try ... then ... then ... except / finally

Antoine solipsis at pitrou.net
Thu Oct 12 10:25:40 CEST 2006


Well I'm sorry for polluting the list with another wild idea.

It often happens that you have to do some cleanup of multiple resources,
but those cleanup functions may raise an exception. Yet you wanna clean
all the resources. So you end up writing something like this :

def finish(self):
    try:
        self.db_transaction.commit()
    finally:
        try:
            self.tmpoutfile.close()
        finally:
            (etc.)

Needless to say that as soon as you have two or more resources, it becomes
quite ugly.

I thought it would be nice to have an idiom where several blocks of code
are tried in order, regardless of whether they throw an exception or not:

try:
    self.db_transaction.commit()
then:
    self.tmpoutfile.close()
then:
    self.destroy_shared_memory_handle()
except Exception, e:
    logging.error("an exception occurred in cleanup: %s", e)

Now, there are two questions I'm wondering about:
- is it necessary? have I missed an existing idiom for doing this as nicely?
- if several exceptions are raised (one for each block of code), what is
caught in the "except" statement? The last raised exception (possibly
chained to the previous one, and so on)?

Sorry if it looks really silly.

Regards

Antoine.




More information about the Python-3000 mailing list