What is "finally:" for?

Paul McGuire ptmcg at austin.rr.com
Tue Sep 16 14:28:34 CEST 2008


On Sep 16, 6:25 am, "Max Ivanov" <ivanov.ma... at gmail.com> wrote:
> Hi all!
> When and where I should use try-except-finally statement? What is the
> difference between:
> --------
> try:
>   A...
> except:
>   B....
> finally:
>   C...
> --------
>
> and
> -------
> try:
>   A...
> except:
>   B....
> C...

If B raises or rethrows another exception, finally: ensures that C
still gets called.  In the second form that you give, C would not get
called.  Here is one way to use try-except-finally:

try:
    open database
    do database stuff
except DatabaseException, de:
    log exception
    throw
finally:
    close database

Or

try:
    transaction = new database transaction
    do database stuff
    do more database stuff
    commit transaction
    transaction = None
except DatabaseException, de:
    log exception
    throw
finally:
    if transaction:
        rollback transaction


If you are allocating a resource, lock, file, database, etc., then
exception-safe coding style is to get the resource in a try: and
release the resource in finally:

-- Paul



More information about the Python-list mailing list