See the traceback module, specifically the format_exc() function. Here.

import traceback

try:
    raise ValueError
except ValueError:
    tb = traceback.format_exc()
else:
    tb = "No error"
finally:
    print(tb)
Answer from kindall on Stack Overflow
Top answer
1 of 12
914

See the traceback module, specifically the format_exc() function. Here.

import traceback

try:
    raise ValueError
except ValueError:
    tb = traceback.format_exc()
else:
    tb = "No error"
finally:
    print(tb)
2 of 12
130

Let's create a decently complicated stacktrace, in order to demonstrate that we get the full stacktrace:

def raise_error():
    raise RuntimeError('something bad happened!')

def do_something_that_might_error():
    raise_error()

Logging the full stacktrace

A best practice is to have a logger set up for your module. It will know the name of the module and be able to change levels (among other attributes, such as handlers)

import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

And we can use this logger to get the error:

try:
    do_something_that_might_error()
except Exception as error:
    logger.exception(error)

Which logs:

ERROR:__main__:something bad happened!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

And so we get the same output as when we have an error:

>>> do_something_that_might_error()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

Getting just the string

If you really just want the string, use the traceback.format_exc function instead, demonstrating logging the string here:

import traceback
try:
    do_something_that_might_error()
except Exception as error:
    just_the_string = traceback.format_exc()
    logger.debug(just_the_string)

Which logs:

DEBUG:__main__:Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
This module provides a standard interface to extract, format and print stack traces of Python programs. It is more flexible than the interpreter’s default traceback display, and therefore makes it possible to configure certain aspects of the output. Finally, it contains a utility for capturing enough information about an exception to print it later, without the need to save a reference to the actual exception.
Discussions

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
Catch and print full Python exception traceback without halting/exiting the program - Stack Overflow
I think that this only works if ... you try getting the traceback before raising an exception object that you create, which you might want to do in some designs. 2023-07-07T13:21:49.917Z+00:00 ... So, repeating what herve-guerin asked in Nov 22, 2017 -- the python traceback only returns the last call level (i.e., only g()): how do you succeed to return several level of the stack (i.e., including ... More on stackoverflow.com
🌐 stackoverflow.com
How do I get the stack trace from an Exception Object in Python? - Stack Overflow
How can I get the full stack trace from the Exception object itself? Consider the following code as reduced example of the problem: last_exception = None try: raise Exception('foo failed') ex... More on stackoverflow.com
🌐 stackoverflow.com
How do you get stack traces for errors?
So there’s a good reason for go not really having this feature, because it’s not super useful most of the time. Errors are not unexpected exceptions. They should always be handled somewhere in your code, and at that point you can decide what additional info is relevant for your error log. It’s a different concept than exception handling in other languages. I typically just wrap my log message with some info about where the error originated from/was handled More on reddit.com
🌐 r/golang
48
17
January 28, 2024
🌐
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.print_exc() is a simple way to print the full exception stack trace directly to the console. It is useful when debugging code interactively or logging errors in basic scripts.
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
July 3, 2026 - If we just want the stack trace on its own, we will need to take a more manual approach, using Python’s built-in inspect module to iterate through each frame of the exception’s traceback object. For example: import inspect def print_stacktrace(exception): stacktrace = exception.__traceback__ for frame in inspect.getinnerframes(stacktrace): filename = frame.filename lineno = frame.lineno function = frame.function code_context = frame.code_context code_context = code_context[0].strip() if code_context else "No code context" print(f"File \"{filename}\", line {lineno}, in {function}") print(f" {code_context}")
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 29, 2019 - In 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. Below is an example to illustrate this situation: ... Here, greet() gets ...
🌐
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 - You can extract, format, and print stack traces with the Python traceback module. Tracebacks are read from the bottom up. The exception or error encountered is always on the last line of the traceback.
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
An IDE may convert the elements of the stack trace into a clickable list that lets the user browse the source. The examples below use the module traceback_example.py (provided in the source package for PyMOTW). The contents are: import traceback import sys def produce_exception(recursion_level=2): sys.stdout.flush() if recursion_level: produce_exception(recursion_level-1) else: raise RuntimeError() def call_function(f, recursion_level=2): if recursion_level: return call_function(f, recursion_level-1) else: return f()
Find elsewhere
🌐
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 - 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 ...
🌐
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 the first printed traceback generated by the python interpreter. Then we have caught exceptions using try-except block. We have then retrieved traceback from the error object using traceback attribute of the error object and have given it to print_tb() method which prints a stack trace.
🌐
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: ...
🌐
The Blog at Ayyjohn
ayyjohn.com › posts › anatomy-of-a-python-stack-trace
How to Read Python Stack Traces | The Blog at Ayyjohn
November 14, 2021 - Traceback (most recent call last): ...ithub.io/code_examples/python/stack_traces.py", line 2, in get_username return user['useranme'] KeyError: 'useranme' Bummer, but simple enough. First, the actual anatomy. A stack trace starts with the actual Exception thrown in Pyth...
🌐
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.

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!")
🌐
Sentry
sentry.io › sentry answers › python › analyze python stack traces
How to Read Python Stack Traces and Tracebacks | Sentry
August 15, 2024 - You can try this by running the following command to open the script in Python’s default debugger, pdb: ... In the shell that appears, use the command s (or step) to repeatedly step through the code until the exception is encountered.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › python-try-except-print-error
How to print as exception in Python
July 31, 2023 - If you want to print more detailed information about an exception, you can use the traceback module. The traceback module provides a number of functions that can be used to print the stack trace of an exception.
🌐
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
🌐
SentinelOne
sentinelone.com › blog › data platform › python stack trace: understanding it and using it to debug
Python Stack Trace: Understanding it and Using it to Debug
October 27, 2022 - When you run the program with python example.py, it should return this stack trace: As you can see, this stack trace contains a lot of information about what’s gone wrong. First of all, it tells you what type of error has occurred: NameError. This type of exception tells us that we’ve referenced a variable that doesn’t exist.
🌐
Stefaan Lippens
stefaanlippens.net › python-traceback-in-catch
Get stacktrace in Python catch body - Stefaan Lippens inserts content here
February 14, 2013 - So you have some Python code in a try-catch, and you want the typical Python stacktrace (aka traceback, aka backtrace) in a way you can manipulate? ... import traceback import logging try: stuff() except Exception: # Just print traceback print "something went wrong, here is some info:" traceback.print_exc() # Get traceback as a string and do something with it error = traceback.format_exc() print error.upper() # Log it through logging channel logging.error('Ooops', exc_info=True)