[BangPypers] Nested try-catch

Anand Chitipothu anandology at gmail.com
Wed Oct 7 06:54:51 CEST 2009


> Well, i am wondering why you are extracting the exc_info() rather than
> saving off the exception object itself:
> try:
>    f()
> except Exception, e
>    saved = e
>    try:
>        g()
>    except:
>        pass # ignore
>    raise e
>
> I have not tested this on 3.0 but i am assuming this should work. If it
> doesn't try using finally:
>
> try:
>    f()
> except Exception, e
>    saved = e
>    try:
>        g()
>    except:
>        pass # ignore
>    finally:
>        raise e

You miss the traceback if you re-raise the exception. It produces this output:

$ python b.py
Traceback (most recent call last):
  File "b.py", line 17, in <module>
    raise e
Exception: f

Instead of this:

$ python 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

When an exception is raised, traceback is taken from the current stack
unless a traceback object is provided to it. I'm using sys.exc_info()
to get the trackback of the original exception and using it when
re-raising the exception.

http://docs.python.org/reference/simple_stmts.html#raise

And there is no need to add "saved = e" as the exception is already
available as variable e.

Anand


More information about the BangPypers mailing list