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
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)ยถ
๐ŸŒ
ProgramCreek
programcreek.com โ€บ python โ€บ example โ€บ 106 โ€บ traceback.print_exc
Python Examples of traceback.print_exc
def test_import_error_custom_func(self): restore_config_file() try: shutil.copy(zmirror_file('config_default.py'), zmirror_file('config.py')) try: self.reload_zmirror({"custom_text_rewriter_enable": True, "enable_custom_access_cookie_generate_and_verify": True, "identity_verify_required": True, }) except: import traceback traceback.print_exc() os.remove(zmirror_file('config.py')) except: pass copy_default_config_file()
Discussions

Exceptions & Logging
It entirely depends on the behaviour you want, which in turn depends on what kind of application this is and how serious the error is. If this is a command-line script for example, and this is a crucial part of the flow, then there's no point logging and continuing because the script can't work without this step. You should probably just let the error be raised. But for example if this is a web app, and this is just one of the operations it can do but it needs to continue to run even if this fails, then yes by all mean catch and log - but don't forget to also return an error message to the user. More on reddit.com
๐ŸŒ r/learnpython
9
5
November 13, 2024
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
๐ŸŒ
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_
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
April 7, 2025 - Traceback (most recent call last): ... ZeroDivisionError: division by zero ยท Explanation: This code attempts to divide by zero inside a try block, which raises a ZeroDivisionError....
๐ŸŒ
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 - print_exc(limit=None, file=None, chain=True) - This method whenever called will print the last exception which had happened in the program. Please make a note that parameter limit, file, and chain are present in multiple methods of traceback ...
Find elsewhere
๐ŸŒ
Read the Docs
stackless.readthedocs.io โ€บ en โ€บ 2.7-slp โ€บ library โ€บ traceback.html
28.10. traceback โ€” Print or retrieve a stack traceback โ€” Stackless-Python 2.7.15 documentation
It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a โ€œwrapperโ€ around the interpreter. The module uses traceback objects โ€” this is the object type that is stored in the variables sys.exc_traceback (deprecated) and sys.last_traceback and returned as the third item from sys.exc_info().
๐ŸŒ
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('print_exc() with no exception:') traceback.print_exc(file=sys.stdout) print() try: produce_exception() except Exception as 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: $ python3 traceback_print_exc.py print_exc() with no exception: NoneType: None print_exc(): Traceback (most recent call las
๐ŸŒ
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): ...
๐ŸŒ
Python
docs.python.org โ€บ 3.3 โ€บ library โ€บ traceback.html
28.9. traceback โ€” Print or retrieve a stack traceback โ€” Python 3.3.7 documentation
This is useful when you want to print stack traces under program control, such as in a โ€œwrapperโ€ around the interpreter. The module uses traceback objects โ€” this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-print-traceback-from-exception
Python Print Traceback from Exception: A Comprehensive Guide - CodeRivers
February 22, 2026 - The traceback.print_exc() function prints the full traceback of the most recent exception that has been caught, including the line numbers where the error occurred and the sequence of function calls. In real-world applications, it is often better to log tracebacks rather than just printing them.
๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ traceback.html
29.9. traceback โ€” Print or retrieve a stack traceback โ€” Python 3.4.10 documentation
June 16, 2019 - This is useful when you want to print stack traces under program control, such as in a โ€œwrapperโ€ around the interpreter. The module uses traceback objects โ€” this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ python program to print stack trace
Python Program to Print Stack Trace - Scaler Topics
January 6, 2023 - 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. The last line confirms that the entire code executes without hindrance. ... In the following example, since the ...
๐ŸŒ
O'Reilly
oreilly.com โ€บ library โ€บ view โ€บ python-cookbook โ€บ 0596001673 โ€บ ch14s05.html
Getting More Information from Tracebacks - Python Cookbook [Book]
July 19, 2002 - """ tb = sys.exc_info( )[2] while 1: if not tb.tb_next: break tb = tb.tb_next stack = [] f = tb.tb_frame while f: stack.append(f) f = f.f_back stack.reverse( ) traceback.print_exc( ) print "Locals by frame, innermost last" for frame in stack: print print "Frame %s in %s at line %s" % (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno) for key, value in frame.f_locals.items( ): print "\t s = " % key, # We have to be VERY careful not to cause a new error in our error # printer!
Authors: Alex MartelliDavid Ascher
Published: 2002
Pages: 608
๐ŸŒ
Jython
jython.org โ€บ jython-old-sites โ€บ docs โ€บ library โ€บ traceback.html
26.7. traceback โ€” Print or retrieve a stack traceback โ€” Jython v2.5.2 documentation
It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a โ€œwrapperโ€ around the interpreter. The module uses traceback objects โ€” this is the object type that is stored in the variables sys.exc_traceback (deprecated) and sys.last_traceback and returned as the third item from sys.exc_info().
๐ŸŒ
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 - Here's how you can print the traceback of an error in Python: 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 ...
๐ŸŒ
Real Python
realpython.com โ€บ python-traceback
Understanding the Python Traceback โ€“ Real Python
July 29, 2019 - Instead, it has been misspelled as someon in the print() call. Note: This tutorial assumes you understand Python exceptions. If you are unfamiliar or just want a refresher, then you should check out Python Exceptions: An Introduction. When you run this program, youโ€™ll get the following traceback: ... $ python example.py Traceback (most recent call last): File "/path/to/example.py", line 4, in <module> greet('Chad') File "/path/to/example.py", line 2, in greet print('Hello, ' + someon) NameError: name 'someon' is not defined
๐ŸŒ
Martin Heinz
martinheinz.dev โ€บ blog โ€บ 66
Creating Beautiful Tracebacks with Python's Exception Hooks | Martin Heinz | Personal Website & Blog
February 1, 2022 - This function - called Exception Hook - is then used to output any relevant information to standard output using the 3 arguments it receives - type, value and traceback. Let's now look at a minimal example to see how this works: import sys def exception_hook(exc_type, exc_value, tb): print('Traceback:') filename = tb.tb_frame.f_code.co_filename name = tb.tb_frame.f_code.co_name line_no = tb.tb_lineno print(f"File {filename} line {line_no}, in {name}") # Exception type and value print(f"{exc_type.__name__}, Message: {exc_value}") sys.excepthook = exception_hook