I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.
I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a string its full description and the stack trace that caused the error (simply all we use to see on the console). I need this string to print it to a text box in the GUI.
Something like this:
try: method_that_can_raise_an_exception(params) except Exception as e: print_to_textbox(complete_exception_description(e))
The problem is: what is the function complete_exception_description
?
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.
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.
Example: Convert stack trace to a string In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer. Then, we simply convert it to string using toString() method.
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.
See the traceback
module, specifically the format_exc()
function. Here.
import traceback try: raise ValueError except ValueError: tb = traceback.format_exc() else: tb = "No error" finally: print tb
Let's create a decently complicated stacktrace, in order to demonstrate that we get the full stacktrace:
def raise_error(): raise RuntimeError('something bad happened!') def do_something_that_might_error(): raise_error()
A best practice is to have a logger set up for your module. It will know the name of the module and be able to change levels (among other attributes, such as handlers)
import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__)
And we can use this logger to get the error:
try: do_something_that_might_error() except Exception as error: logger.exception(error)
Which logs:
ERROR:__main__:something bad happened! Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 2, in do_something_that_might_error File "<stdin>", line 2, in raise_error RuntimeError: something bad happened!
And so we get the same output as when we have an error:
>>> do_something_that_might_error() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in do_something_that_might_error File "<stdin>", line 2, in raise_error RuntimeError: something bad happened!
If you really just want the string, use the traceback.format_exc
function instead, demonstrating logging the string here:
import traceback try: do_something_that_might_error() except Exception as error: just_the_string = traceback.format_exc() logger.debug(just_the_string)
Which logs:
DEBUG:__main__:Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 2, in do_something_that_might_error File "<stdin>", line 2, in raise_error RuntimeError: something bad happened!
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