Print Full Python Traceback Without Halting Program

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 block intercepting and halting the program?

Yeah, I’ve done this before. The easiest way is by using traceback.print_exc(). It’s straightforward and gets the job done. You can directly print the full Python traceback inside the except block without stopping your program.

import traceback

try:
    do_stuff()
except Exception as err:
    print("Caught an exception:")
    traceback.print_exc()  # Prints the full traceback

This method mimics Python’s default exception handling by printing the complete traceback to the standard output. The program continues running without halting.

Here’s a slightly more flexible way that I often use. Instead of directly printing the traceback, you can use traceback.format_exc() to get it as a string. This is useful if you want to log it or manipulate it further.

import traceback

try:
    do_stuff()
except Exception as err:
    traceback_str = traceback.format_exc()  # Capture the traceback as a string
    print("Caught an exception:", traceback_str)

This approach gives you a clean way to handle the Python traceback, especially when you want to store it for later use or customize its output.

Another option, especially for production use, is integrating this with the logging module. If you’re already logging errors, logging.exception() is the way to go—it automatically includes the Python traceback.

import logging

logging.basicConfig(level=logging.ERROR)

try:
    do_stuff()
except Exception as err:
    logging.exception("Caught an exception:")  # Logs the exception with traceback

This method is perfect for scenarios where you need detailed error reporting without cluttering your console output. Plus, it scales well with larger applications where logging is a must.