Sub topic 5
Inspecting the exception with as
This chapter assumes you can write a basic try/except statement and know that exceptions are objects created from classes. Here you will learn how to get at the exception object that Python raised, and what you can safely do with it.
Binding the exception to a name
Adding as name to an except clause binds the caught exception object to that name. Without it, you know that an error occurred, but you can't see its details.
def read_config(path):
try:
with open(path) as f:
return f.read()
except FileNotFoundError as exc:
print(f"type: {type(exc).__name__}")
print(f"message: {exc}")
print(f"errno: {exc.errno}, file: {exc.filename}")
return None
read_config("missing.txt")The name exc is a convention, and e and err are also common. The object has the type you matched, so it carries the attributes of that type. FileNotFoundError is a subclass of OSError, which adds errno and filename.
What you can read from the object
| Expression | What it gives you |
|---|---|
| `str(exc)` | The human-readable message |
| `repr(exc)` | The class name and arguments, such as `ValueError('bad')` |
| `exc.args` | A tuple of the arguments passed when the exception was created |
| `exc.__traceback__` | The traceback object for where the error happened |
| `exc.__cause__` | The exception named in `raise ... from`, if any |
| `exc.__context__` | The exception being handled when this one was raised, if any |
Prefer repr(exc) in logs. For some exceptions, str(exc) is empty or misleading, so the class name matters.
try:
{}["port"]
except KeyError as exc:
print(str(exc))
print(exc.args[0])
print(repr(exc))str(exc) prints 'port' with the quotes, because KeyError formats its message using repr of the key. exc.args[0] gives you the key itself.
The name disappears after the block
Python deletes the bound name when the except block ends. This prevents a reference cycle between the exception, its traceback, and the frame that holds the name.
try:
int("x")
except ValueError as exc:
print("inside:", exc)
saved = exc
try:
print(exc)
except NameError as err:
print("after:", err)
print("kept:", repr(saved))The second try raises NameError because exc no longer exists. If you need the exception later, assign it to another name inside the block, as saved does here. Keep such references short-lived. The exception holds its traceback, which holds every frame and local variable along the path.
Common errors
- Using the name after the block. This raises
NameError, or it hides an older variable with the same name that the block just deleted. - Printing only
str(exc)for exceptions such asKeyError, where the output loses context. Userepr(exc)ortype(exc).__name__. - Reading an attribute that only some types have. In
except (OSError, ValueError) as exc,exc.errnofails when the exception is aValueError. Use separate handlers when you need type-specific attributes. - Binding a name you never use. Leave out
aswhen you don't need the object.
Exercise
What happens when this code runs, and why? try: int("abc") except ValueError as err: pass print(err)
Show answer
It raises NameError: name 'err' is not defined. Python deletes the name bound by "as" when the except block ends. To use the exception afterwards, assign it to another name inside the block, for example saved = err.