else and finally in Python
Four blocks, four jobs: try, except, else for success, finally for cleanup.
def read_number(text):
try:
value = int(text)
except ValueError:
print("could not parse")
return None
else:
print("parsed cleanly")
return value
finally:
print(f"done with {text!r}")
print(read_number("42"))
print(read_number("no"))
How it works
elseruns only when no exception was raised.finallyruns on every path, including a return.- Keeping the risky line alone in
tryis the point ofelse.
Keywords and builtins used here
defelseexceptfinallyintprintread_numberreturntry
The run, in numbers
- Lines
- 15
- Characters to type
- 234
- Tokens
- 65
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 39 seconds.
Step 2 of 3 in Errors in depth, step 63 of 72 in Language basics.