try / except
try runs a block of code, and if it fails with a specific error, except decides what to do instead of stopping the program.
Used in 67 lessons of the course, from 00.02.
When Python hits an error, it raises an exception and the program stops. With try you say: "attempt this". With except you say: "if it fails with this error, do this instead".
try:
int("abc")
except ValueError:
print("not a number")
Read it like this: the code inside try: runs normally. If everything goes well, Python skips except. If a ValueError happens, Python jumps straight to the except block and carries on after it.
Name the error you expect, not a generic one. That way you only catch what you know how to handle, and other errors still show up. In the course you will see try: in many lessons, starting in 00.02, to handle failures such as a response that doesn't have the expected shape.
Reach for it when: an operation can fail for a reason you expect (malformed data, a missing key) and you know what to do in that case.
Examples
Common mistake
data = {"name": "Ana"}
try:
print(data["age"])
except ValueError:
print("missing")Why: A missing key raises KeyError, not ValueError. The except doesn't match, so the error goes on.
How to write it: Catch the right error: except KeyError:.
