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
February 22, 2026 - The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
Top answer
1 of 16
1525

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
879

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!")
Discussions

Print Full Python Traceback Without Halting Program - TestMu AI Community
How can I catch and print the full Python traceback without halting or exiting the program? I want to catch exceptions and log them, but without terminating the program. For example: try: do_stuff() except Exception as err: print(Exception, err) # I want to print the entire traceback here, ... More on community.testmu.ai
🌐 community.testmu.ai
0
November 17, 2024
python - Storing and printing an exception with traceback? - Stack Overflow
Use the traceback module. For Python 3.10 and up, you can just write ... 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: More on stackoverflow.com
🌐 stackoverflow.com
Disable printing in unit tests
You could use redirect_stdout like this: from contextlib import redirect_stdout from io import StringIO import unittest import main class DivisionTests(unittest.TestCase): def test_zero_division(self): """Fails if the program doesn't exit when dividing by zero.""" with redirect_stdout(StringIO()) as stdout: with self.assertRaises(SystemExit) as e: main.divide(1, 0) self.assertEqual(stdout.getvalue(), 'Error: Cannot divide by zero.\n') self.assertEqual(e.exception.code, 1) More on reddit.com
🌐 r/learnpython
6
2
November 26, 2016
How do I print a custom error message without Python returning a traceback?
The problem you have is a bit different. You are catching the ValueError. The traceback of the ValueError is not printed on the console as you would want. However another exception occurs that you simply don't catch. In your positive number code for example you are defining retrieve_positive_number inside of the try block. However you try to do something with it outside of it, although it is only visible in the scope of the try block. That's why you get a NameError. The variable is not defined. Try to move the code for the positive case (the user enters a valid number) inside of the try block. More on reddit.com
🌐 r/pythonhelp
2
3
August 3, 2021
People also ask

What does it mean by "print an exception" in Python?
Printing an exception in Python refers to displaying exact records approximately errors that arise in the course of the execution of a program. These facts include the form of the exception, an error message, and often a traceback showing the sequence of calls that caused the mistake.
🌐
taglineinfotech.com
taglineinfotech.com › home › how do i print an exception in python?
How do I Print an Exception in Python? - Tagline Infotech
Why is printing exceptions crucial?
Printing exceptions is essential for debugging. It affords insights into what went wrong within the code, supporting developers in discovering and dealing with errors correctly. The records printed enable an understanding of the character and context of the exception.
🌐
taglineinfotech.com
taglineinfotech.com › home › how do i print an exception in python?
How do I Print an Exception in Python? - Tagline Infotech
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Traceback (most recent call last): ... a try block, which raises a ZeroDivisionError. The except block catches the exception and prints the detailed error traceback using traceback.print_exc(), helping in debugging by displaying ...
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
import traceback import sys from traceback_example import produce_exception print 'print_exc() with no exception:' traceback.print_exc(file=sys.stdout) print try: produce_exception() except Exception, err: print 'print_exc():' traceback.print_exc(file=sys.stdout) print print 'print_exc(1):' traceback.print_exc(limit=1, file=sys.stdout) In this example, the file handle for sys.stdout is substituted so the informational and traceback messages are mingled correctly: $ python traceback_print_exc.py print_exc() with no exception: None print_exc(): Traceback (most recent call last): File "traceback_
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 31, 2023 - Python prints a traceback when an exception is raised in your code. The traceback output can be a bit overwhelming if you’re seeing it for the first time or you don’t know what it’s telling you.
🌐
Tagline Infotech
taglineinfotech.com › home › how do i print an exception in python?
How do I Print an Exception in Python? - Tagline Infotech
December 31, 2025 - The traceback.format_exc() function will print a detailed stack trace of the exception. When using Python try except print error to handle exceptions, the ability to print the exception stack trace provides insight into the python print error ...
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
April 15, 2024 - We can use traceback.print_exception to print the traceback of an exception object we pass to it, along with the usual exception information. This function has three required arguments: the exception’s class, the exception object, and the ...
🌐
Carmatec
carmatec.com › home › how to print and debug exceptions in python like a pro
How to Print and Debug Exceptions in Python Like a Pro
December 31, 2025 - Output: Exception Type: <class ‘ZeroDivisionError’> Exception Message: division by zero Traceback: <traceback object at 0x7f8b5c0b7c40> This method provides detailed information about the exception, which is useful for logging or custom error handling. Note that sys.exc_info() returns a tuple containing the exception type, value, and traceback object. Python’s try-except block supports additional clauses: else and finally.
🌐
Coursera
coursera.org › tutorials › python-traceback
How to Print, Read, and Format a Python Traceback | Coursera
Python provides a traceback when an exception is raised. You can extract, format, and print stack traces with the Python traceback module.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › python-try-except-print-error
How to print as exception in Python
July 31, 2023 - Traceback (most recent call last): ... The traceback.format_exc() function will print a detailed stack trace of the exception. The stack trace will show the line numbers of the code where the exception occurred, as well as the function calls ...
🌐
Scaler
scaler.com › home › topics › python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
January 6, 2023 - The traceback module in Python provides functionalities to deal with the stack trace. The methods used to print stack trace are print_exception() and print_exc().
🌐
TestMu AI Community
community.testmu.ai › ask a question
Print Full Python Traceback Without Halting Program - TestMu AI Community
November 17, 2024 - How can I catch and print the full Python traceback without halting or exiting the program? I want to catch exceptions and log them, but without terminating the program. For example: try: do_stuff() except Exception as err: print(Exception, err) # I want to print the entire traceback here, # not just the exception name and details How can I print the exact same output that is generated when the exception is raised, including the full Python traceback, without the try/except bl...
🌐
GitHub
github.com › orgs › micropython › discussions › 13593
How to print traceback of last unhandled exception when reaching Micropython prompt · micropython · Discussion #13593
February 4, 2024 - If I have the Python REPL open during program execution and an unhandled exception occurs, the traceback will already be printed on the console so I know exactly where in the code the exception occurred. But if the exception happens without the REPL open, then the traceback printout will be lost.
🌐
Real Python
realpython.com › ref › stdlib › traceback
traceback | Python Standard Library – Real Python
The Python traceback module provides utilities for working with error tracebacks in Python programs. 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): ...
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)?

🌐
Python Morsels
pythonmorsels.com › reading-tracebacks-in-python
Deciphering Python's Traceback (most recent call last) - Python Morsels
January 3, 2022 - When exceptions go unhandled, Python prints a traceback. Tracebacks are read from the bottom upward. The last line describes what happened and lines above describe where it happened.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
>>> try: ... raise NameError('HiThere') ... except NameError: ... print('An exception flew by!') ... raise ... An exception flew by! Traceback (most recent call last): File "<stdin>", line 2, in <module> raise NameError('HiThere') NameError: HiThere · If an unhandled exception occurs inside an except section, it will have the exception being handled attached to it and included in the error message: