python · level 3 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
data once, at the door, then trust it inside.
Anything from outside your program can be wrong: typed answers, files, form fields, API replies. Validate it the moment it arrives, at the door, and turn it into clean values. Code further in can then trust what it receives.
Write each check as a : an if at the top that raises an error at once. Raise a , a class of your own like BadAge, so callers can catch exactly your problem and nothing else. Its body is pass, which means nothing more to add.
class BadAge(ValueError):
pass
def parse_age(text):
text = text.strip()
if not text.isdigit() or int(text) > 130:
raise BadAge(f"not a real age: {text}")
return int(text)
for answer in [" 42 ", "forty", "-3", "200"]:
try:
print("age", parse_age(answer))
except BadAge as problem:
print("rejected,", problem) Inheriting from ValueError means older code that catches ValueError still catches your error too.
guess first
Which except catches it? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class OrderError(ValueError):
pass
def place(qty):
if qty < 1:
raise OrderError("order at least one")
return f"ordered {qty}"
for qty in [2, 0]:
try:
print(place(qty))
except ValueError as problem:
print("caught:", problem, type(problem).__name__)
your turn
Your turn. Guard a new username.
Fill the first blank with the custom exception to raise. In the second, try a username of your own with at least three letters or digits.
fix it
The guard never gets a chance. Fix it!
- The crash is a plain
ValueError, not yourBadQuantity. Which line fails first? int(text)runs before the guard clause gets a chance to check anything.- Move
qty = int(text)below theifblock, so the guard comes first, then run.
nailed it
your program checks everything at the door. :D
- Validate outside data the moment it arrives.
- Guard clauses raise an error early and keep the rest simple.
- A custom exception lets callers catch exactly your problem.
new words in your collection
- validate
- guard clause
- custom exception
This lesson isn’t saved. A free account remembers every lesson you finish.