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
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True: run_user_code(envdir)
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!")
๐ŸŒ
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 - Python provides a traceback when an exception is raised. You can extract, format, and print stack traces with the Python traceback module.
๐ŸŒ
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_
๐ŸŒ
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): File "/home/guest/sandbox/Solution.py", line 4, in <module> 1 / 0 # division by zero ~~^~~ ZeroDivisionError: division by zero ยท Explanation: This code attempts to divide by zero inside 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 where the error occurred.
๐ŸŒ
Real Python
realpython.com โ€บ python-traceback
Understanding the Python Traceback โ€“ Real Python
July 29, 2019 - Tracebacks are known by many names, ... Python, the term used is traceback. When your program results in an exception, Python will print the current traceback to help you know what went wrong....
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output. traceback.print_exception(etype, value, tb, limit = None, file = None, chain = True) : Prints exception ...
Find elsewhere
๐ŸŒ
Python
docs.python.org โ€บ 3.8 โ€บ library โ€บ traceback.html
traceback โ€” Print or retrieve a stack traceback โ€” Python 3.8.20 documentation
Print up to limit stack trace entries from traceback object tb (starting from the callerโ€™s frame) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed.
๐ŸŒ
Python
docs.python.org โ€บ 3.10 โ€บ library โ€บ traceback.html
traceback โ€” Print or retrieve a stack traceback โ€” Python 3.10.19 documentation
The optional limit argument has the same meaning as for print_tb(). If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception. Changed in version 3.5: The etype argument is ignored and inferred from the type of value. Changed in version 3.10: The etype parameter has been renamed to exc and is now positional-only. traceback.print_exc(limit=None, file=None, chain=True)
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - In addition to printing stack traces, several other methods for tracing function execution in Python are available, as discussed in this answer. The function traceback.print_stack will print a stack trace at the current point in our scriptโ€™s invocation. The optional limit parameter allows us to control how many entries are printed โ€” by default, the entire stack trace will be printed.
๐ŸŒ
Jython
jython.org โ€บ jython-old-sites โ€บ docs โ€บ library โ€บ traceback.html
26.7. traceback โ€” Print or retrieve a stack traceback โ€” Jython v2.5.2 documentation
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. ... print โ€œException in user code:โ€ print โ€˜-โ€˜*60 traceback.print_exc(file=sys.stdout) print โ€˜-โ€˜*60
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
January 6, 2023 - In the following code snippet, the value of the denominator is set to 0 to view how Python print stack trace works. The traceback.print_exc() method in the except block prints the program's location, the line where the error was encountered, and the name and relevant information about the error.
๐ŸŒ
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): ...
๐ŸŒ
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 - We have first artificially generated error and then printed the error stack by calling print_last() method. ... --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-8-ff29a4977585> in <module> ----> 1 out = 10/0 ZeroDivisionError: division by zero ... Traceback (most recent call last): File "/home/sunny/anaconda3/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3418, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-8-ff29a4977585>", line 1, in <module> out = 10/0 ZeroDivisionError: division by zero
๐ŸŒ
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.

๐ŸŒ
University of New Brunswick
cs.unb.ca โ€บ ~bremner โ€บ teaching โ€บ cs2613 โ€บ books โ€บ python3-doc โ€บ library โ€บ traceback.html
traceback โ€” Print or retrieve a stack traceback โ€” Python 3.9.2 documentation
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module. import sys, traceback def run_user_code(envdir): source = input(">>> ") try: exec(source, envdir) except Exception: print("Exception in user code:") print("-"*60) traceback.print_exc(file=sys.stdout) print("-"*60) envdir = {} while True: run_user_code(envdir)
๐ŸŒ
Acid & Base
sceweb.sce.uhcl.edu โ€บ helm โ€บ WEBPAGE-Python โ€บ documentation โ€บ python_tutorial โ€บ lib โ€บ module-traceback.html
3.6 traceback -- Print or retrieve a stack traceback.
This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (innermost last):"; (2) it prints the exception type and value after the stack trace; (3) if type 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.
๐ŸŒ
MachineLearningMastery
machinelearningmastery.com โ€บ home โ€บ blog โ€บ understanding traceback in python
Understanding Traceback in Python - MachineLearningMastery.com
June 21, 2022 - The typo is at the last line, where the closing bracket should be at the end of the line, not before any +. The return value of the print() function is a Python None object. And adding something to None will trigger an exception. If you run this program using the Python interpreter, you will see this: The lines starting with โ€œTraceback (most recent call last):โ€ are the traceback.
๐ŸŒ
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.