How do you catch and print a full Python exception traceback without stopping execution? | A1Lab@MZeeshanM to PythonEnglish •
edit-2
5 days ago

How do you catch and print a full Python exception traceback without stopping execution?

message-square
0

Catch Exception as err inside a try ... except block and call traceback.print_exc() (to print the full stack trace directly to sys.stderr), traceback.format_exc() (to capture the traceback as a str), or logging.exception("Context message") (to record both your log message and the full traceback automatically)—allowing the program to continue executing cleanly afterward.

Basic Example

import logging
import traceback


def divide(a: float, b: float) -> float:
    return a / b


# 1. Print full traceback directly to stderr and continue running
try:
    divide(10, 0)
except Exception:
    traceback.print_exc()

print("Program kept running after traceback.print_exc()!")


# 2. Capture the full traceback as a string (for custom formatting, APIs, or DB storage)
try:
    int("invalid_number")
except ValueError:
    tb_text = traceback.format_exc()
    print(f"Captured {len(tb_text)} chars of traceback:\n{tb_text}")


# 3. Recommended for production apps: logging.exception() logs message + full traceback
logging.basicConfig(level=logging.ERROR)
try:
    {}["missing_key"]
except KeyError:
    logging.exception("Failed to look up configuration key")

Key Details & Edge Cases

  • Catch Exception (or specific exceptions), NOT bare except: or BaseException:
    • Writing a bare except: or catching BaseException traps KeyboardInterrupt (Ctrl+C), SystemExit (sys.exit()), and GeneratorExit, preventing users or process managers from shutting down your script. Always catch except Exception: (or a narrower exception tuple like except (ValueError, KeyError):).
  • Capture and format an exception object outside an active except block (traceback.format_exception(err)):
    • Inside an except block, traceback.print_exc() and traceback.format_exc() inspect sys.exception() automatically.
    • When passing a caught exception object err to another function or worker callback (Python 3.10+), pass err directly to traceback.format_exception(err) (returns list[str]) or traceback.print_exception(err):
      def report_error(err: BaseException) -> str:
          return "".join(traceback.format_exception(err))
      
  • Preserving chained exceptions (raise ... from ...): Both traceback.print_exc() and logging.exception() automatically render full exception chains—including explicit causes (During handling of the above exception, another exception occurred) and implicit context (The above exception was the direct cause of the following exception).
  • Printing to sys.stdout instead of sys.stderr: traceback.print_exc() writes to sys.stderr by default. If your console or log collector only captures stdout, pass file=sys.stdout (traceback.print_exc(file=sys.stdout)).
  • Inspecting stack frames without raising an exception (traceback.format_stack()): If you want to print the current call stack at a checkpoint when no exception has occurred, call traceback.print_stack() (instead of print_exc(), which prints NoneType: None when called outside an except block).

Comparison of Traceback Printing & Capture Methods

Method Module Destination / Return Type Requires Active except Block? Best Used When
traceback.print_exc() traceback Prints directly to sys.stderr (None) Yes Quick CLI scripts and debugging loops where you want standard stderr tracebacks.
traceback.format_exc() traceback Returns formatted str Yes Storing tracebacks in variables, JSON error responses, emails, or databases.
logging.exception(msg) logging Writes ERROR log + traceback to configured handlers Yes Production applications using Python’s logging framework (logger.exception(...)).
traceback.format_exception(err) traceback Returns list[str] from an Exception instance No (takes err object) Formatting exception objects passed into callbacks, queues, or asyncio task handlers.
logger.error(msg, exc_info=True) logging Writes ERROR (or custom level) + traceback Yes (or pass exc_info=err) Attaching tracebacks to custom log levels (logger.warning(..., exc_info=True)).