A level · 4 exercises
Python exceptions
A try block runs code that might fail; its except catches the error and lets the program carry on, instead of stopping.
Catch the error you expect, by name: ValueError for int("abc"), ZeroDivisionError for dividing by 0.
for line in ["4", "x", "7"]:
try:
print(int(line) * 2)
except ValueError:
print("not a number")Watch for: A bare except: hides every mistake, your own typing errors too. Name the error.
Exercises
- Safe divisionDivide pairs of values.Advanced
- Count the bad linesRead lines until the line END.Advanced
- Real datesCheck dates written as YYYY-MM-DD.Advanced
- Careful calculatorWork out expressions "a op b" where op is +, -, * or /.Advanced