×

python · level 2 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.