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 bareexcept:orBaseException:- Writing a bare
except:or catchingBaseExceptiontrapsKeyboardInterrupt(Ctrl+C),SystemExit(sys.exit()), andGeneratorExit, preventing users or process managers from shutting down your script. Always catchexcept Exception:(or a narrower exception tuple likeexcept (ValueError, KeyError):).
- Writing a bare
- Capture and format an exception object outside an active
exceptblock (traceback.format_exception(err)):- Inside an
exceptblock,traceback.print_exc()andtraceback.format_exc()inspectsys.exception()automatically. - When passing a caught exception object
errto another function or worker callback (Python 3.10+), passerrdirectly totraceback.format_exception(err)(returnslist[str]) ortraceback.print_exception(err):def report_error(err: BaseException) -> str: return "".join(traceback.format_exception(err))
- Inside an
- Preserving chained exceptions (
raise ... from ...): Bothtraceback.print_exc()andlogging.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.stdoutinstead ofsys.stderr:traceback.print_exc()writes tosys.stderrby default. If your console or log collector only capturesstdout, passfile=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, calltraceback.print_stack()(instead ofprint_exc(), which printsNoneType: Nonewhen called outside anexceptblock).
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)). |
You must log in or register to comment.
