What is "finally:" for?

Ant antroy at gmail.com
Tue Sep 16 08:33:23 EDT 2008


On Sep 16, 12:30 pm, Andreas Kaiser <kaiser.voc... at gmail.com> wrote:
> On 16 Sep., 13:25, "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...
> > --------
>
> It does A if no exception or B if an exception occurs. THEN it does
> always C.

Rather it runs the code in A. If an exception is thrown in A, B is
then run. C is run regardless.

> > -------
> > try:
> >   A...
> > except:
> >   B....
> > C...
>
> If an exception occurs, C is never reaching.

Whether or not C runs will depend on what code is present in B (e.g.
it could return, or throw a different exception).

Typically you will use a finally clause if there is some cleanup that
should occur regardless of whether an exception is thrown. For
example:

def getNumbers(filename):
    numbers = []

    fh = open("test.txt") # Should contain lines of numbers
    try:
        for line in fh:
            if line.strip():
                numbers.append(int(line.strip()))
    except ValueError, e:
        return None
    finally:
        fh.close()

    return numbers


This ensures that open files are closed for example.

--
Ant.



More information about the Python-list mailing list