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
Print Stack Trace in Python Using traceback Module The traceback. format_exc() method returns a string that contains the information about exception and stack trace entries from the traceback object. We can use the format_exc() method to print the stack trace with the try and except statements.
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With