Search code examples
pythonexceptionsystraceback

Why exc_traceback returns None


sys.exc_info() returns a tuple (type , value, traceback).
so sys.exc_info()[2] is our traceback object.

Why it does not catch exceptions traceback with this code:

import sys

try:
    1/0
except ZeroDivisionError:
    print sys.exc_info()[2].tb_frame.f_back

tb_frame and f_back usage has been explained here: Frame Objects


Solution

  • You see None because there is no outer frame. You're executing this directly, so the current frame is the last frame. To demonstrate this, I created a demo.py:

    import sys
    
    try:
        1/0
    except ZeroDivisionError:
        print sys.exc_info()[2].tb_frame.f_back
    

    which should look familiar, and a trivial caller.py:

    import demo
    

    Now see the difference:

    $ python demo.py
    None
    
    $ python caller.py
    <frame object at 0x10bc34c20>
    

    In the second case, where there is an outer frame (i.e. caller.py), you don't see None.