HOWTO · Python

How to Print an Exception in Python

Learn how to print an exception in Python, choose between a message and a full traceback, and avoid common exception-handling mistakes.

On this page

Use print(exception) when you only need the error message. Use traceback.print_exc() inside an active except block when you need the complete traceback, including the file and line that raised the error. Keep the exception-specific handling narrow, and use logging rather than print() for diagnostics that must be retained.

Catch the exception as a variable and pass it to print(). This is the shortest way to show what went wrong:

try:
    result = 10 / 0
except ZeroDivisionError as exc:
    print("Could not calculate result:", exc)

Output:

Could not calculate result: division by zero

The exception object is converted to its message text. This example catches ZeroDivisionError specifically, which makes it less likely that an unrelated programming error will be hidden. If several errors need the same treatment, list their types in a tuple, such as except (TypeError, ValueError) as exc:.

The message may not show where an error originated. Import Python’s traceback module and call print_exc() while the handler is active:

import traceback

try:
    values = [1, 2]
    value = values[3]
except IndexError:
    traceback.print_exc()

The output includes the exception type, message, file, and line that failed. A traceback is more useful than a message when the exception comes from several nested function calls.

print_exc() reads the exception currently being handled. Calling it after the except block has finished, or when no exception is active, does not recover a previous traceback; it can print NoneType: None. Keep the call in the handler, or save the exception and use print_exception() for explicit control.

Control traceback formatting explicitly

traceback.print_exception() accepts an exception object and can write to a chosen stream. This is useful when the exception must be formatted or redirected:

import sys
import traceback

try:
    int("not a number")
except ValueError as exc:
    traceback.print_exception(exc, file=sys.stdout)

To build text instead of printing immediately, use traceback.format_exception(exc):

import traceback

try:
    raise RuntimeError("configuration is missing")
except RuntimeError as exc:
    formatted = "".join(traceback.format_exception(exc))
    print(formatted)

The traceback functions preserve exception chaining by default, so a raise ... from ... chain can show both the original and the new error. Limit the traceback or disable chaining only when the output contract requires it; removing context can make diagnosis harder.

Custom exceptions and logging

Define a custom exception when callers need to distinguish a domain failure from a built-in error. Catch that type and print its message in the same way:

class ConfigurationError(Exception):
    pass

try:
    raise ConfigurationError("API key is missing")
except ConfigurationError as exc:
    print("Configuration failed:", exc)

For an application or service, prefer logging.exception() inside the handler. It records the message and the active traceback, and logging handlers can route it to a file or monitoring system:

import logging

try:
    load_settings()
except Exception:
    logging.exception("Loading settings failed")

Replace load_settings() with the operation that can fail. The example intentionally shows a broad Exception catch only at a logging boundary; normal application logic should catch the narrow exception types it can actually handle.

Common mistakes and FAQ

  • A bare except: also catches KeyboardInterrupt and SystemExit. Avoid it unless you have a specific reason to handle BaseException subclasses.
  • Do not print only a generic message and then silently continue when the program cannot produce a valid result. Re-raise the exception or return an explicit failure when appropriate.
  • type(exc) shows the concrete class, while str(exc) shows the human-readable message. repr(exc) can reveal a more diagnostic representation.
  • If output is going to a log, use logging.exception() from inside the handler. If you only need a short interactive diagnostic, print(exc) is sufficient.
  • traceback.print_exc() is for the currently handled exception; traceback.print_exception(exc) is the clearer choice when you retain an exception object and need explicit formatting or output control.

These patterns work with Python’s built-in exception machinery and require no third-party package. The correct choice depends on whether the reader needs a message, the complete call path, formatted text, or durable application logging.