34

How to print the stack trace of an exception object in Python?

Note that the question is NOT about printing stack trace of LAST exception. Exception object may be saved at some distant point of time in the past.

1

2 Answers 2

49

It's a bit inconvenient, but you can use traceback.print_exception. Given an exception ex:

traceback.print_exception(type(ex), ex, ex.__traceback__)

Example:

import traceback

try:
    1/0
except Exception as ex:
    traceback.print_exception(type(ex), ex, ex.__traceback__)

# output:
# Traceback (most recent call last):
#   File "untitled.py", line 4, in <module>
#     1/0
# ZeroDivisionError: division by zero
Sign up to request clarification or add additional context in comments.

6 Comments

It's a bit inconvenient why? looks okay to me
@Jean-FrançoisFabre Well, there really is no reason why it's necessary to pass 3 arguments to that function. If a function like print_exception(ex) existed, that would be much nicer.
Other useful function would be print_exc() which get info about exception(s) from sys.info
IMHO, exception.traceback() is a more cleaner OOPs-like syntax.
|
4

you can manually iterate through the __traceback__ attribute to print lines & files:

def function():
    raise ValueError("flfkl")

try:
    function()
except Exception as e:
    traceback = e.__traceback__
    while traceback:
        print("{}: {}".format(traceback.tb_frame.f_code.co_filename,traceback.tb_lineno))
        traceback = traceback.tb_next

Comments

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.