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
🌐
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): ... ‘variable_that_does_not_exist’ is not defined The traceback.format_exc() function will print a detailed stack trace of the exception....
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
February 22, 2026 - Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. traceback.format_exception_only(exc, /, [value, ]*, show_group=False)¶
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
Print traceback without an exception
Hello, in CPython, there is a way to print a traceback outside of an exception, through traceback.print_stack() function. What would it take to add similar functionality to micropython? More on github.com
🌐 github.com
10
April 2, 2019
debugging - print python stack trace without exception being raised - Stack Overflow
Note, that traceback.format_stack() returns the stacktrace as a formatted list of strings, so you can slice it anyway you want. To get the last few elements of the stacktrace you could do: ... Where N is the number of levels you are interested in. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 2 Python: How to print the stacktrace of an exception object without ... More on stackoverflow.com
🌐 stackoverflow.com
python - Print an error message without printing a traceback and close the program when a condition is not met - Stack Overflow
I have seen sys.exit(), but that also prints out a giant block of red text, unless I am not using it correctly. I don't want to catch the exception in my loop because there are other classes in the same module in which I need to implement something like this. ... President James K. Polk · 42.3k3535 gold badges115115 silver badges149149 bronze badges ... You can turn off the traceback by limiting its depth. ... In Python ... More on stackoverflow.com
🌐 stackoverflow.com
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!")
🌐
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_
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
April 15, 2024 - Print stack traces manually, at different points in the script’s execution, without raising an exception. Print the stack trace of a provided exception object. We can do both of these things using Python’s built-in traceback module, which provides stack traces in a manner identical to the ...
🌐
Rich
rich.readthedocs.io › en › latest › traceback.html
Traceback — Rich 14.1.0 documentation
Rich can render Python tracebacks with syntax highlighting and formatting. Rich tracebacks are easier to read and show more code than standard Python tracebacks. To see an example of a Rich traceback, running the following command: ... The print_exception() method will print a traceback for ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - TracebackeException Class : TracebackException objects are created from actual exceptions to capture data for later printing. class traceback.TracebackException(exc_type, exc_value, exc_traceback, *, limit = None, lookup_lines = True, capture_locals = False) The class TracebackException contains the following objects: __cause__ : A TracebackException of the original __cause__. __context__ : A TracebackException of the original __context__.
Find elsewhere
🌐
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...
🌐
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. But the Python traceback has a wealth of information that can help you diagnose and fix the ...
🌐
GitHub
github.com › micropython › micropython › issues › 4667
Print traceback without an exception · Issue #4667 · micropython/micropython
April 2, 2019 - Hello, in CPython, there is a way to print a traceback outside of an exception, through traceback.print_stack() function. What would it take to add similar functionality to micropython?
Author   mzakharocsc
🌐
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.
🌐
GitHub
gist.github.com › nepsilon › 107971fb4b65c9cea7c58cbdcea2abb6
Python: How to print the full traceback without exiting the program? — First published in fullweb.io issue #81
December 17, 2022 - import traceback try: raise Exception(“nop”) except Exception as ex: traceback.print_exc() # Output: Traceback (most recent call last): File “<stdin>”, line 2, in <module> Exception: nop · The traceback module also works well with Python 2.x.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - It is useful when debugging code interactively or logging errors in basic scripts. It automatically captures the latest exception and prints its traceback without requiring extra parameters.
🌐
Coderz Column
coderzcolumn.com › tutorials › python › traceback-how-to-extract-format-and-print-error-stack-traces-in-python
traceback - How to Extract, Format, and Print Error Stack Traces in Python by Sunny Solanki
January 14, 2021 - There is three kinds of methods available with the traceback module. print_*() - These methods are used to print stack traces to the desired output medium (standard error, standard output, file, etc).
Top answer
1 of 9
77

You can turn off the traceback by limiting its depth.

Python 2.x

import sys
sys.tracebacklimit = 0

Python 3.x

In Python 3.5.2 and 3.6.1, setting tracebacklimit to 0 does not seem to have the intended effect. This is a known bug. Note that -1 doesn't work either. Setting it to None does however seem to work, at least for now.

In Python 3.6.2 and above you should set tracebacklimit to 0 or -1, as setting it to None does not disable the traceback output.

Python 3.6.1 and below results:

>>> import sys

>>> sys.tracebacklimit = 0
>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception

>>> sys.tracebacklimit = -1
>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception

>>> sys.tracebacklimit = None
>>> raise Exception
Exception

Python 3.6.2 and above results:

>>> import sys

>>> sys.tracebacklimit = 0
>>> raise Exception
Exception

>>> sys.tracebacklimit = -1
>>> raise Exception
Exception

>>> sys.tracebacklimit = None
>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception

Nevertheless, for better or worse, if multiple exceptions are raised, they can all still be printed. For example:

socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
2 of 9
42

You can use SystemExit exception:

except Exception as err:
    raise SystemExit(err)

See the documentation on SystemExit for more details.

🌐
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.

🌐
Python Module of the Week
pymotw.com › 3 › traceback › index.html
traceback — Exceptions and Stack Traces
import traceback import sys from traceback_example import produce_exception print('with no exception:') exc_type, exc_value, exc_tb = sys.exc_info() tbe = traceback.TracebackException(exc_type, exc_value, exc_tb) print(''.join(tbe.format())) print('\nwith exception:') try: produce_exception() except Exception as err: exc_type, exc_value, exc_tb = sys.exc_info() tbe = traceback.TracebackException( exc_type, exc_value, exc_tb, ) print(''.join(tbe.format())) print('\nexception only:') print(''.join(tbe.format_exception_only())) The format() method produces a formatted version of the full tracebac