Sub topic 5
Inspecting the exception with as
This chapter assumes you can write a basic try/except and know that handlers are matched by class, as the earlier chapters covered. It covers what except ... as name gives you, what you can read from the bound object, and the rule that deletes the name when the handler ends.
What as does
A bare except ValueError: tells you that something went wrong. Adding as exc also gives you the exception object, so you can read its message and attributes and pass it to other code.
try:
int("abc")
except ValueError as exc:
print(type(exc).__name__)
print(exc.args)
print(str(exc))
print(repr(exc))This prints:
ValueError
("invalid literal for int() with base 10: 'abc'",)
invalid literal for int() with base 10: 'abc'
ValueError("invalid literal for int() with base 10: 'abc'")The name after as is an ordinary variable. exc and e are common choices, and err is useful when exc is already taken. The bound object is the same instance Python raised, not a copy.
Reading the exception
Every exception has a few attributes in common, and many types add their own.
| Attribute | What it holds |
|---|---|
| `args` | Tuple of the arguments passed to the constructor. |
| `str(exc)` | Human-readable message, built from `args`. |
| `repr(exc)` | Class name plus `args`, which is unambiguous and good for logs. |
| `__traceback__` | The traceback object for the frames the exception passed through. |
| `__cause__` | The exception named in `raise ... from`, or `None`. |
| `__context__` | The exception being handled when this one was raised, or `None`. |
| `__notes__` | List of strings added with `add_note()` (Python 3.11+). |
Specific types carry extra fields. OSError and its subclasses expose errno, strerror, and filename:
try:
open("missing.txt")
except OSError as exc:
print(type(exc).__name__)
print(exc.errno, exc.strerror, exc.filename)On Linux and macOS this prints FileNotFoundError, then 2 No such file or directory missing.txt. Checking exc.errno lets one OSError handler react differently to "not found" and "permission denied". The errno module has named constants such as errno.ENOENT. In practice, catching FileNotFoundError or PermissionError directly is clearer. Other examples are JSONDecodeError.lineno and .colno, UnicodeDecodeError.start and .reason, and AttributeError.name and .obj (Python 3.10+). Check the documentation of the type you catch.
str versus repr
str(exc) can hide the exception's type and sometimes its meaning. A KeyError for a missing key prints only the key, and an exception raised with no message prints an empty string:
try:
{}["x"]
except KeyError as exc:
print(str(exc))
print(repr(exc))
try:
raise RuntimeError
except RuntimeError as exc:
print(f"[{exc}]")
print(f"[{exc!r}]")The first pair prints 'x' and KeyError('x'). The second pair prints [] and [RuntimeError()]. When you format an exception into a message, use {exc!r}, or f"{type(exc).__name__}: {exc}" when you want a readable form that keeps the type.
Binding with several types
as works with a tuple of classes. The name holds whichever exception actually occurred, so type(exc) tells you which one it was:
def read_number(text):
try:
return float(text)
except (TypeError, ValueError) as exc:
print(f"{type(exc).__name__}: {exc}")
return None
read_number("x")
read_number(None)The output is ValueError: could not convert string to float: 'x' and then TypeError: float() argument must be a string or a real number, not 'NoneType'.
The name disappears after the handler
When the handler finishes, Python deletes the name. The behavior is equivalent to wrapping the handler body in try: ... finally: del exc. This is the most common surprise with as:
try:
{}["x"]
except KeyError as exc:
saved = exc
print(repr(saved))
try:
print(exc)
except NameError as err:
print(err)The output is KeyError('x') and then name 'exc' is not defined. The handler copied the exception to saved, which survives. Inside a function the same mistake raises UnboundLocalError instead, which is a subclass of NameError.
The reason is memory. An exception holds a traceback, the traceback holds the frames, and the frames hold their local variables. If exc were a local variable, the frame would refer to the exception and the exception would refer back to the frame. That reference cycle would stay alive until the garbage collector ran. Deleting the name breaks the cycle as soon as the handler ends.
The deletion also affects any variable that already had that name:
exc = "keep me"
try:
1 / 0
except ZeroDivisionError as exc:
pass
print(exc)This raises NameError. The handler overwrote the old exc, and the cleanup then deleted it. Pick a name that nothing else in the scope uses.
Keeping the exception for later
Sometimes you want to collect errors in a loop and report them together. Store the object in a longer-lived container:
def parse_all(items):
results = []
failures = []
for item in items:
try:
results.append(int(item))
except ValueError as exc:
failures.append((item, exc))
return results, failures
values, failures = parse_all(["1", "two", "3", "4.5"])
print(values)
for item, exc in failures:
print(f"{item!r}: {exc}")The list holds the exception objects and keeps them alive. Each exception also keeps its traceback, and through it the frames and their locals, for as long as you hold it. For a long-lived list this can use a lot of memory, so store repr(exc) or the fields you need when the traceback is not required.
Adding context with notes
Python 3.11 added add_note(), which appends a string to the exception's __notes__ list. Notes appear in the traceback. You can add context at a lower level without wrapping the exception in a new type:
import traceback
def parse(line):
return int(line)
try:
parse("x")
except ValueError as exc:
exc.add_note("while reading line 7")
print("".join(traceback.format_exception(exc)))The printed traceback ends with the ValueError message followed by while reading line 7. Passing the exception as the only argument to traceback.format_exception works in Python 3.10 and later. On earlier versions, use the three-argument form.
Sending the exception to logs
The as name is also how you hand an exception to the logging module with the full traceback:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def fetch(value):
try:
return int(value)
except ValueError as exc:
logger.error("could not parse %r", value, exc_info=exc)
return 0
fetch("zz")exc_info accepts an exception instance, a tuple, or True. Inside a handler, logger.exception(...) does the same thing without needing the name. Use as when you also need the object for something else, such as a custom message or a stored failure list.
Common mistakes
- Using the name after the block, which gives
NameErrororUnboundLocalError. - Reusing a variable name that existed before the
try, which silently deletes it. - Printing only
str(exc), which loses the type and can be empty. - Calling
print(exc)to "log" an error and so losing the traceback. Useloggingwithexc_info. - Binding the same name in nested handlers. The inner handler's cleanup deletes the name, so the outer handler can no longer read it. Use different names.
Exercise
What does this code print, and why? exc = "keep me" try: 1 / 0 except ZeroDivisionError as exc: pass print(exc)
Show answer
It raises NameError: name 'exc' is not defined. The except clause rebinds exc to the ZeroDivisionError, and when the handler ends Python deletes the name, which also removes the earlier "keep me" value. Use a different name in the as clause, or copy the exception to another variable inside the handler.
Exercise
A handler for except KeyError as exc: prints str(exc) for a missing key "port" and the output is 'port'. What would you print instead to make the message clearer, and which expression shows the exception type?
Show answer
Print repr(exc), which gives KeyError('port'), or build a message such as f"{type(exc).__name__}: {exc}". Either one includes the exception type, which str(exc) leaves out.