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 bareassert False),StopIteration,TimeoutError, orKeyErrorwithout arguments—producestr(err) == "". - Always format logs or user-facing diagnostics as
f"{type(err).__name__}: {err}"(orrepr(err), which outputs"AssertionError()") so you never end up with a blank error string.
- Exceptions raised without a message—such as
KeyErrorwraps its message in extra single quotes (str(KeyError("user_id"))$\rightarrow$"'user_id'"):KeyError.__str__()callsrepr()on its first argument so an empty-string key""is distinguishable from no message. To read the unquoted missing key name directly, accesserr.args[0](whenerr.argsis non-empty) instead ofstr(err).
- Deprecated
err.messageattribute (AttributeErrorin Python 3):- Python 2’s
.messageattribute was removed in Python 3—accessingerr.messageon standard exceptions raisesAttributeError: '...' object has no attribute 'message'. Always usestr(err)orerr.args.
- Python 2’s
- Exceptions raised with multiple arguments (
raise CustomError("Failed", 503)):- When multiple arguments are passed to an exception constructor,
err.argsstores the full tuple("Failed", 503), whilestr(err)formats the tuple string"('Failed', 503)". Readerr.args[0]if you want only the primary message string.
- When multiple arguments are passed to an exception constructor,
- 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 errso Python attaches the original exception tonew_err.__cause__and displays both tracebacks automatically.
- When wrapping a low-level error in a custom exception, use
- Logging exceptions cleanly with
logging.exception():- Inside an
exceptblock, callinglogger.exception("Operation failed")automatically captures and logs the exception type,str(err)message, and full stack trace atERRORlevel without manual string formatting.
- Inside an
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. |
You must log in or register to comment.
