8

How can I get the full stack trace from the Exception object itself?

Consider the following code as reduced example of the problem:

last_exception = None
try:
    raise Exception('foo failed')
except Exception as e:
    print "Exception Stack Trace %s" % e

1 Answer 1

5

The stack trace itself is not stored in the exception object itself. However, you can print the stack trace of the last recent exception using sys.exc_info() and the traceback module. Example:

import sys
import traceback

try:
    raise Exception('foo failed')
except Exception as e:
    traceback.print_tb(*sys.exc_info())

If you do not want to display the stack trace immediately, it should be possible to store the return value of sys.exc_info() somewhere.

Sign up to request clarification or add additional context in comments.

2 Comments

Storing the result of sys.exc_info() blindly would result in badness... from docs.python.org/library/sys.html#sys.exc_info - "Warning Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference."
Also, instead of traceback.print_tb(*sys.exc_info()), I would recommend docs.python.org/library/traceback.html#traceback.format_exc to get a formatted traceback string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.