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 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - # importing module import traceback # declaring array A = [1, 2, 3, 4] try: value = A[5] except: # printing stack trace traceback.print_exc() # out of try-except # this statement is to show that the program continues # normally after the exception is handled print("end of program") Output : Traceback (most recent call last): File "C:/Python27/van.py", line 8, in value = A[5] IndexError: list index out of range end of program >>>
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - 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.
🌐
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) ...
🌐
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)
🌐
TimOnWeb
timonweb.com › tim kamanin — a django/wagtail developer › python › how to print exception traceback in python
How to print exception traceback in Python ⚡ | TimOnWeb
January 30, 2021 - import traceback try: raise Boom('This is where our code blows') except Exception: # here's how you get a traceback output traceback_output = traceback.format_exc() # Now you can print it, or send it, or save it in a file print(traceback_output)
🌐
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.
🌐
One Two Bytes
onetwobytes.com › 2021 › 11 › 12 › print-stack-trace-python-exception
Printing Stack Traces in Python Exceptions: A Comprehensive Guide | One Two Bytes
February 6, 2024 - Encountering errors in Python is inevitable. But with stack traces, you can pinpoint the exact location of an exception and diagnose issues effectively. Here’s a step-by-step guide: ... try: processEvent() # Call the function that might raise an exception except Exception as e: print("Error encountered:", e) traceback.print_exc() # Print the detailed stack trace
🌐
Hrekov
hrekov.com › blog › print-stack-traces-python
Python Exception Handling: Complete Guide to try-except, Propagation, Hierarchy, and Tracebacks | Web Tools, Production APIs & Technical Blog | Hrekov
December 15, 2025 - This guide provides a comprehensive ... for tracebacks. Python provides a structured block mechanism to monitor code for runtime exceptions and define recovery workflows. def safe_divide(numerator: float, denominator: float): try: result = numerator / denominator except ZeroDivisionError: print("Error: Cannot ...
🌐
Real Python
realpython.com › ref › stdlib › traceback
traceback | Python Standard Library – Real Python
Colorizes traceback output by default in Python 3.13 and later, configurable through the PYTHON_COLORS and NO_COLOR environment variables · Captures complete exception information for debugging and logging ... >>> import traceback >>> try: ... int("abc") ... except ValueError: ... print(trace...