How do you capture and read the error message from a caught Python exception? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you capture and read the error message from a caught Python exception?

message-square
0

Bind the caught exception to a variable using except ExceptionType as err: and convert it to a string with str(err) (or f"{type(err).__name__}: {err}" to include the exception class name)—inspecting err.args when you need the raw arguments passed to the exception constructor or traceback.format_exc() when you also want the full stack trace as a string.

Basic Example

import traceback

try:
    result = int("not_a_number")
# 1. Recommended: Bind the exception instance with `as err` and read str(err)
except ValueError as err:
    message = str(err)
    print(f"Message only: {message}")
    # Output: Message only: invalid literal for int() with base 10: 'not_a_number'

    print(f"Type + message: {type(err).__name__}: {err}")
    # Output: Type + message: ValueError: invalid literal for int() with base 10: 'not_a_number'

    # 2. Raw constructor arguments tuple
    print(f"Raw args: {err.args}")
    # Output: Raw args: ("invalid literal for int() with base 10: 'not_a_number'",)

    # 3. Full traceback string (file, line number, call stack, type, and message)
    full_trace = traceback.format_exc()

Key Details & Edge Cases

  • str(err) can be empty ("") for certain built-in exceptions:
    • Exceptions raised without a message—such as AssertionError (from bare assert False), StopIteration, TimeoutError, or KeyError without arguments—produce str(err) == "".
    • Always format logs or user-facing diagnostics as f"{type(err).__name__}: {err}" (or repr(err), which outputs "AssertionError()") so you never end up with a blank error string.
  • KeyError wraps its message in extra single quotes (str(KeyError("user_id")) $\rightarrow$ "'user_id'"):
    • KeyError.__str__() calls repr() on its first argument so an empty-string key "" is distinguishable from no message. To read the unquoted missing key name directly, access err.args[0] (when err.args is non-empty) instead of str(err).
  • Deprecated err.message attribute (AttributeError in Python 3):
    • Python 2’s .message attribute was removed in Python 3—accessing err.message on standard exceptions raises AttributeError: '...' object has no attribute 'message'. Always use str(err) or err.args.
  • Exceptions raised with multiple arguments (raise CustomError("Failed", 503)):
    • When multiple arguments are passed to an exception constructor, err.args stores the full tuple ("Failed", 503), while str(err) formats the tuple string "('Failed', 503)". Read err.args[0] if you want only the primary message string.
  • Preserving original error details when chaining exceptions (raise ... from err):
    • When wrapping a low-level error in a custom exception, use raise ServiceError("DB query failed") from err so Python attaches the original exception to new_err.__cause__ and displays both tracebacks automatically.
  • Logging exceptions cleanly with logging.exception():
    • Inside an except block, calling logger.exception("Operation failed") automatically captures and logs the exception type, str(err) message, and full stack trace at ERROR level without manual string formatting.

Comparison of Exception Information Extraction Methods

Expression / Method Example Output (int("abc")) Behavior When Raised with No Message (assert False) Best Used When
str(err) "invalid literal for int()..." "" (empty string) Extracting the plain human-readable error message for UIs or API responses.
f"{type(err).__name__}: {err}" "ValueError: invalid literal..." "AssertionError: " Concise single-line error logs where empty messages still identify the failure.
repr(err) "ValueError(\"invalid literal...\")" "AssertionError()" Debugging and structured logs needing unambiguous type + quoted argument representation.
err.args ("invalid literal for int()...",) () (empty tuple) Accessing raw positional arguments (e.g., unquoted KeyError keys via err.args[0]).
traceback.format_exc() Multi-line traceback + ValueError: ... Multi-line traceback + AssertionError Capturing the complete call stack, file paths, and line numbers into a string.
logging.exception(msg) Logs msg + full traceback to logger Logs msg + AssertionError traceback Production application logging inside an except block.