try: finally: question

djw donald.welch at hp.com
Tue Jul 6 13:05:38 EDT 2004


Hi, Folks-

I have a question regarding the "proper" use of try: finally:... Consider
some code like this:

d = Device.open()
try:
        d.someMethodThatCanRaiseError(...)
        if SomeCondition:
                raise Error # Error is subclass of Exception
        d.someMethodThatCanRaiseError(...)
        ... lots of other methods on d that can raise Error


finally:
        d.close()


When I run this code, and an Error is raised, I get traceback (which I don't
want) and the program terminates (which I don't want). However, putting in
each method that can raise Error into a try: except: block doesn't help,
because I need to re-raise Error to break out of the block and get the
finally: to be triggered:


d = Device.open()
try:
        try:
                d.someMethodThatCanRaiseError(...)
        except Error:
                # Do something here
                raise Error
        if SomeCondition:
                raise Error # Error is subclass of Exception
        try:
                d.someMethodThatCanRaiseError(...)
        except Error:
                # Do something here
                raise Error

        ... lots of other methods on d that can raise Error


finally:
        d.close()


I almost feel like I need a goto statement! Am I missing something about
finally:, or is it really not altogther very useful in practice?

Thanks,

-Don




More information about the Python-list mailing list