try, except, finally in Python
Handling failure: catch what you expect, re-raise what you don't.
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return None
except TypeError as exc:
raise ValueError(f"bad operands: {exc}")
else:
return result
finally:
print("attempted division")
half = safe_divide(1, 2)
nothing = safe_divide(1, 0)
How it works
- Each
exceptclause targets one exception type. elseruns only when nothing was raised.finallyruns on every exit path.- Catching
TypeErrorre-raises as a clearer error.
Keywords and builtins used here
asdefelseexceptfinallyprintraisereturnsafe_dividetry
The run, in numbers
- Lines
- 15
- Characters to type
- 258
- Tokens
- 64
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 38 seconds.
Step 4 of 7 in Iterators, errors & files, step 47 of 72 in Language basics.