python · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
and catch an error before it stops your program.
Some errors only happen while a program runs, often because of what someone typed. These are exceptions. int("ten") causes a , and without help your program stops dead.
Wrap the risky lines in a try block. If they work, Python skips the except block. If a ValueError happens, Python jumps straight to except ValueError:, runs those lines instead, and carries on below.
Name the error you expect. A bare except: catches everything, including mistakes you never meant to hide.
answers = ["12", "ten", "7"]
for answer in answers:
try:
number = int(answer)
print(f"{number} doubled is {number * 2}")
except ValueError:
print(f"'{answer}' is not a whole number") Lines after the error inside try are skipped, which is why nothing is doubled for ten.
guess first
Which lines run? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
try:
print("Start")
age = int("twelve")
print("Converted!")
except ValueError:
print("That was not a number")
print("Finished")
your turn
Your turn. Keep asking until you get a number.
The loop asks for an age until the answer is a whole number. Fill in the error that int() causes for text like old. We will answer old, then 12.
fix it
The VAT calculator still crashes. Can you fix it?
- Read the last line of the error. Which kind of error really happened?
float("free")causes a ValueError, but theexceptline is waiting for a TypeError, so it never catches it.- Change TypeError to ValueError on line 4, then run.
nailed it
you caught your first exception. :D
- Put risky lines in
tryand the rescue plan inexcept. - Name the exact error you expect, like
except ValueError:. - After
exceptruns, the program carries on below.
new words in your collection
- exception
- try
- except
- ValueError
This lesson isn’t saved. A free account remembers every lesson you finish.