[BangPypers] Nested try-catch

Anand Chitipothu anandology at gmail.com
Tue Oct 6 17:54:25 CEST 2009


I encountered a tricky situation with nested try-catch. Here is the sample code:

def f():
    raise Exception("f")

def g():
    raise Exception("g")

try:
    f()
except:
    # do cleanup
    try:
        g()
    except:
        pass # ignore
    raise

This code raises Exception("g") instead of Exception("f") as intended.
The first exception is lost when the second one is generated. However,
this issue has been resolved in Python 3.0.

$ python2.5 a.py
Traceback (most recent call last):
  File "a.py", line 13, in <module>
    g()
  File "a.py", line 6, in g
    raise Exception("g")
Exception: g

$ python3.0 a.py
Traceback (most recent call last):
  File "a.py", line 9, in <module>
    f()
  File "a.py", line 3, in f
    raise Exception("f")
Exception: f

I managed to work-around that problem like this:

try:
    f()
except:
    x = sys.exc_info()
    # do cleanup
    try:
        g()
    except:
        pass # ignore
    raise x[0], x[1], x[2]

It provides exception class, object and traceback to raise instead of
letting raise take the last exception/traceback.

Has anybody else faced similar situation? Any better solutions?

Anand


More information about the BangPypers mailing list