traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
Answer from volting on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ traceback.html
traceback โ€” Print or retrieve a stack traceback โ€” Python 3.14.7 documentation
if tb is not None, it prints a header Traceback (most recent call last): it prints the exception type and value after the stack trace ยท if type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error. Since Python 3.10, instead of passing value and tb, an exception object can be passed as the first argument.
๐ŸŒ
Real Python
realpython.com โ€บ python-traceback
Understanding the Python Traceback โ€“ Real Python
July 29, 2019 - Seeing the AttributeError in the error message line can help you quickly identify which attribute you attempted to access and where to go to fix it. Most of the time, getting this exception indicates that you are probably working with an object that isnโ€™t the type you were expecting: ... >>> a_list = (1, 2) >>> a_list.append(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append'
Discussions

terminal - python3 traceback error - Unix & Linux Stack Exchange
Whenever I mistype any command in terminal instead of getting Error:Command not found I get this python message error Traceback (most recent call last): File "/usr/lib/python3.3/site.py", li... More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
October 19, 2013
python - Storing and printing an exception with traceback? - Stack Overflow
After the method returns I want to print the errors in the console. How can I print the exceptions with traceback and the usual uncaught exception formatting? ... Use the traceback module. For Python 3.10 and up, you can just write More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I use Try Except without hiding the stack trace?
repr doesn't give you all the info in the exception. Look at the traceback module for printing them more formatted with full stacktrace. Look at the rich package on PyPI if you want really fancy formatting and colors. More on reddit.com
๐ŸŒ r/pythontips
9
3
September 19, 2025
Blender 3.6 and RebusFarm: Python Traceback error
Im struggling with the same issues ๐Ÿ˜ฉ More on reddit.com
๐ŸŒ r/blender
3
1
November 10, 2023
Top answer
1 of 16
1534

traceback.format_exc() will yield more info if that's what you want.

import traceback

def do_stuff():
    raise Exception("test exception")

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())

This outputs:

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    do_stuff()
  File "main.py", line 5, in do_stuff
    raise Exception("test exception")
Exception: test exception
2 of 16
880

Some other answer have already pointed out the traceback module.

Please notice that with print_exc, in some corner cases, you will not obtain what you would expect. In Python 2.x:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

...will display the traceback of the last exception:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info in a local variable and display it using print_exception:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

Producing:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

Few pitfalls with this though:

  • From the doc of sys_info:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • but, from the same doc:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

... will display:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ stdlib โ€บ traceback
traceback | Python Standard Library โ€“ Real Python
Itโ€™s particularly useful for debugging and error handling, as it allows you to capture and display the call stack of a program when an exception occurs. ... >>> import traceback >>> try: ... {"a": 1}["b"] ... except KeyError: ... traceback.print_exc() Traceback (most recent call last): ... KeyError: 'b' ... Colorizes traceback output by default in Python 3.13 and later, configurable through the PYTHON_COLORS and NO_COLOR environment variables
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 3 โ€บ traceback
traceback โ€” Exceptions and Stack Traces โ€” PyMOTW 3
March 18, 2018 - The return value is a list of entries from each level of the stack represented by the traceback. Each entry is a tuple with four parts: the name of the source file, the line number in that file, the name of the function, and the source text from that line with whitespace stripped (if the source is available). $ python3 traceback_extract_tb.py format_exception(): traceback_extract_tb.py:18:<module>: produce_exception() traceback_example.py :17:produce_exception(): produce_exception(recursion_level - 1) traceback_example.py :17:produce_exception(): produce_exception(recursion_level - 1) traceback_example.py :19:produce_exception(): raise RuntimeError()
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ reading-tracebacks-in-python
Deciphering Python's Traceback (most recent call last) - Python Morsels
January 3, 2022 - So sometimes you'll need to read other frames in your call stack above that bottom one. ... That error message means Python tried to use the + operator between a string and an integer, and that's not allowed.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ traceback
traceback โ€“ Extract, format, and print exceptions and stack traces. - Python Module of the Week
Now available for Python 3! Buy the book! ... The traceback module works with the call stack to produce error messages. A traceback is a stack trace from the point of an exception handler down the call chain to the point where the exception was raised.
Find elsewhere
๐ŸŒ
Coursera
coursera.org โ€บ tutorials โ€บ how to print, read, and format a python traceback
How to Print, Read, and Format a Python Traceback | Coursera
March 10, 2023 - A traceback is a Python module you can use to trace an error back to its source. It reports the function calls made at a specific point in your code. When your code throws (or raises) an exception, Python provides a traceback.
Top answer
1 of 3
17

Use the traceback module. For Python 3.10 and up, you can just write

for exc in errors:
    traceback.print_exception(exc)

On previous versions, traceback.print_exception only supports the old type/value/traceback format, so you'll have to extract type(exc) and exc.__traceback__ yourself:

for exc in errors:
    traceback.print_exception(type(exc), exc, exc.__traceback__)

Also, be aware that Python has a very strange way of building tracebacks, where an entry for a stack frame is added to the traceback when an exception propagates into that stack frame, rather than building the traceback all at once when the exception is created or raised.

This means that an exception's traceback stops at the point where it stopped propagating. When your the_method catches an exception, the exception's traceback will stop at the_method.

2 of 3
1

Exceptions have attributes, just like other objects in Python. You may want to explore the attributes of your exceptions. Consider the following example:

>>> try:
    import some_junk_that_doesnt_exist
except Exception as error:
    print(dir(error))


['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '_not_found', 'args', 'msg', 'name', 'path', 'with_traceback']

This means that for each exception in your list, you can access the exception's attribute. Thus, you can do the following:

for e in err:
    print(e.args)
    print(e.name)
    print(e.msg)

One thing that occurs to me, though, is that the following line shouldn't really append more than one exception to your errors list:

except Exception as e:
     errors.append(e)

Someone else will know better than I would, but isn't Exception always going to be one thing here (unless you're capturing multiple specific exceptions)?

๐ŸŒ
OxRSE
train.rse.ox.ac.uk โ€บ material โ€บ HPCu โ€บ introductory_courses โ€บ python โ€บ 12_errors_and_exceptions
Errors and Exceptions - OxRSE Training - University of Oxford
If you attempt to write to a file that was opened read-only, Python 3 returns an UnsupportedOperationError. More generally, problems with input and output manifest as IOErrors or OSErrors, depending on the version of Python you use. ... -----------------------------------------------------...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. Example : ... # importing the modules import traceback import sys a=3 b=0 try: a/b except Exception as e: exc_type, exc_value, exc_tb = sys.exc_info() tb = traceback.TracebackException(exc_type, exc_value, exc_tb) print(''.join(tb.format_exception_only())) Output :
๐ŸŒ
7-Zip Documentation
documentation.help โ€บ Python-3.6.8 โ€บ traceback.html
29.9. traceback โ€” Print or retrieve a stack traceback - Python 3.6.8 Documentation
Format the exception part of the traceback. The return value is a generator of strings, each ending in a newline. Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the output. New in version 3...
๐ŸŒ
Reddit
reddit.com โ€บ r/pythontips โ€บ how can i use try except without hiding the stack trace?
r/pythontips on Reddit: How can I use Try Except without hiding the stack trace?
September 19, 2025 -

I've been dealing with legacy code that uses Try Excepts. The issue I'm having is that when a failure occurs the stack trace points to the line the Except is on (well the line below that's reporting it).

Code looks a little like this:

try:
  ...
except Exception as e:
  print(f"Error {str(repr(e))}")

Is this legacy code written incorrectly? Is there a reason we don't want to stack trace?

Maybe I'm wrong and this is returning the stacktrace but in a file that I'm not looking at, but I wanted to double check because so far Excepts seem to be a hidderance for me when I'm troubleshooting.

๐ŸŒ
Mouse Vs Python
blog.pythonlibrary.org โ€บ home โ€บ understanding tracebacks in python
Understanding Tracebacks in Python - Mouse Vs Python
January 31, 2020 - You will see this error whenever Python cannot find the module that you are trying to import. Here is an example: >>> import some Traceback (most recent call last): File " ... Here we learn that Python could not find the โ€œsomeโ€ module.
๐ŸŒ
InterServer
interserver.net โ€บ home โ€บ python โ€บ python tracebacks made simple: learn to debug like a pro
Python Tracebacks Made Simple: Learn to Debug Like a Pro - Interserver Tips
April 23, 2026 - These messages show up when Python runs into issues like using a variable that doesnโ€™t exist, dividing by zero, or writing incorrect syntax. ... Traceback (most recent call last): File "main.py", line 1, in print(name) NameError: name 'name' is not defined ยท To understand tracebacks better, it helps to read from the bottom up. The last line usually gives the exact reason for the error, while the lines above show how the program reached that point.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ builtins โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.7 documentation
Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message. ... This method sets tb as the new traceback for the exception and returns the exception object.
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ python-traceback
Python Traceback: How to Read? & Error Types? (with Example)
April 12, 2023 - A Python traceback is used to handle an exception or trace an error that occurred in the line of code. When a Python program has a mistake, the interpreter can create a traceback that provides a series of function calls that went wrong and led ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-traceback
Python Traceback - GeeksforGeeks
July 23, 2020 - Some of the common traceback errors are: ... NameError: NameError occurs when you try to reference some variable which hasnโ€™t been defined in the code. Example: ... Traceback (most recent call last): File "gfg.py", line 5, in print(numb) NameError: name 'numb' is not defined ยท IndexError: An IndexError is raised when a sequence is referenced which is out of range. Example: ... mylist = [1, 2, 3] # Accessing the index out # of range will raise IndexError print(mylist[10]) Output:
๐ŸŒ
Medium
iamdamilare13.medium.com โ€บ exploring-python-tracebacks-types-and-functions-c7c5973abaea
Exploring Python Tracebacks: Types and Functions | by Damilare Daramola | Medium
December 11, 2024 - Specific Error Message: Finally, Python provides the exact type of error and a short description. For example, running the divide function mentioned earlier would result in a traceback like this: --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[1], line 3 1 def divide(x, y): 2 return x / y ----> 3 print(divide(5, 0)) Cell In[1], line 2 1 def divide(x, y): ----> 2 return x / y ZeroDivisionError: division by zero