try / except
Some errors are expected, such as bad user input or dividing by zero. try lets you catch them instead of crashing:
try: n = int(text) except ValueError: n = 0
Catch the specific error you expect, not everything.
A try can also have else and finally blocks, and as e gives you the error object:
try: n = int(text) except ValueError as e: # e holds the error; str(e) is its message print("Bad input:", e) else: # runs only when no error happened print("Got", n) finally: # always runs last, error or not print("Done")
See it run
def read(text): try: n = int(text) except ValueError: n = 0 else: print("parsed", n) finally: print("done") return n read("12") read("hi")
Watch which lines light up on each call: some are skipped.
Practice try / except
Exercise 1
safe_divide(a, b)returnsa / b, orNoneif b is 0 (catchZeroDivisionError).to_int(text)returnsint(text), or0if the text cannot be converted to an integer, such as"hi"or"3.5"(catchValueError).
Exercise 2
Write parse_age(text): return an integer age from 0 through 120 inclusive. Return None for non-integer text or an integer outside that range. Catch ValueError for bad numeric text; do not turn a valid zero into a missing age.
Exercise 3
Write readings_average(texts). Try converting each string with float; skip ValueError entries. Return the mean of valid readings, including zero and negative readings, or None when none are valid. All supplied numeric readings are finite.
Exercise 4
Write parse_qty(text) that returns a list of log messages:
- try
int(text); catchValueError as eand add"error: "followed bystr(e) - in an
elseblock, add"ok: N"with the number - in a
finallyblock, always add"checked"last
So parse_qty("4") returns ["ok: 4", "checked"] and parse_qty("x") returns ["error: invalid literal for int() with base 10: 'x'", "checked"].
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.