except … as e
`except … as e` catches an error and gives it a name so you can read its message or inspect it.
Used in 59 lessons of the course, from 00.02.
When an error happens, Python creates an exception object. With as e you store it in a variable inside the except block.
Read the line as: "catch these error types and call it e". You can use str(e) or an f-string to see the message, or type(e).__name__ to know its class.
The name only exists inside the except block. When the block ends, Python deletes it so the error and its traceback are not kept alive.
The course uses it like this: except (OSError, subprocess.TimeoutExpired) as exc:. A tuple of types catches several errors with one block, and exc tells you which one happened. e and exc are conventions, not requirements.
try:
int("x")
except ValueError as e:
print(e)
Reach for it when: you need the error's message or details to show it, log it, or decide what to do.
Examples
Common mistake
try:
int("x")
except ValueError as e:
pass
print(e)Why: Python deletes `e` when the `except` block ends, so it no longer exists outside.
How to write it: Use e inside the block, or copy it first: error = e.
