Exception handling code (try/except/finally)

From: djw (dwelch_at_vcd.hp.com)
Date: 03/08/05


Date: Mon, 07 Mar 2005 16:04:26 -0800

c.l.p-

I am having trouble understanding how one is supposed to correctly
utilize try:...except:...finally: in real code. If I have a block of
code like:

def foo():
        try:
                ... some code that can raise an exception ...

        finally:
                ... do some cleanup ...
                return something

If any exception occurs in the code inside the try:...finally:, it will
fail silently, which is a bad thing.

So, the obvious thing to do (I think) is:

def foo():
        try:
                try:
                        ... some code that can raise an exception ...
                except someerror:
                        ... handle the error...
        finally:
                ... do some cleanup ...
                return something

But, now the finally doesn't really serve any purpose, if all the
exceptions are handled by except:, finally will never be called as a
result of an exception, only as the last statements of the function.

So, the next step is to do this?

def foo():
        try:
                try:
                        ... some code that can raise an exception ...
                except someerror:
                        ... handle the error...
                        raise someerror
        finally:
                ... do some cleanup ...
                return something

Which, I guess will work, but it feels very awkward. Is this the
preferred/"correct" way to handle this? Is there a more elegant solution?

Also, why is this construct not possible?:

try:
        ... some code that can raise an exception ...
except someerror:
        ... handle the error...
finally:
        ... do cleanup, etc. ...

Thanks,

Don



Relevant Pages

  • Destructors and exceptions
    ... locals appears to be deferred to program exit. ... The only rationale I can think of is to speed up exception ... class Foo: ... def premature_exit: ...
    (comp.lang.python)
  • virtual metaclasses explanation
    ... def ClassA ... class ClassB < ClassC ... stuart = ClassB.methodY ... def m1"foo" end ...
    (comp.lang.ruby)
  • [ANN] main-2.8.3
    ... a class factory and dsl for generating command line programs real ... def runputs 'installing...' ... and auto-generation of usage messages can really ... int(foo): the cast is int, ...
    (comp.lang.ruby)
  • Re: Getting rid of "self."
    ... def __init__: ... > basis of information available at the time the decorator executes. ... I am content with declaring them like the selfless ... foo = _foo ...
    (comp.lang.python)
  • Re: Got SystemStackError exception: stack level too deep
    ... def mail_system ... puts "Got #exception: #" ... SystemStackError exception: stack level too deep"? ... def foo; foo; end ...
    (comp.lang.ruby)