Lesson 14 of 35Python
Python · Lesson 14 · 25 minutes
Catching errors with try
What you'll learn
- Understand when programs crash
- Catch errors with
tryandexcept - Handle different kinds of errors differently
When programs crash
So far every error was the end of your program. Try it and type a word instead of a number:
age = int(input("How old are you? "))
print(f"In 10 years you'll be {age + 10}.")Python stops with a ValueError because “hello” can’t be turned into a number. In a real program (or on a robot!) that shouldn’t happen.
try and except
With try you say: “Give this a go.” If something goes wrong, Python jumps into the except part instead of crashing:
try:
age = int(input("How old are you? "))
print(f"In 10 years you'll be {age + 10}.")
except ValueError:
print("Sorry, that wasn't a number.")
print("The program keeps running!")After except you write which error you want to catch. You already know the names from the error messages.
Several kinds of errors
You can handle different errors differently by writing several except blocks below each other:
numbers = [10, 20, 30]
try:
position = int(input("Which position (0–2)? "))
print(f"There you'll find {numbers[position]}.")
except ValueError:
print("Please enter a number.")
except IndexError:
print("That position doesn't exist.")| Error | When it happens |
|---|---|
ValueError | int("abc") – the value doesn’t fit |
ZeroDivisionError | 5 / 0 |
IndexError | the position in the list doesn’t exist |
KeyError | the key in the dictionary doesn’t exist |
Ask until it fits
With while True and break you keep asking until a valid input arrives. break ends the loop immediately:
while True:
try:
number = int(input("Number between 1 and 10: "))
if 1 <= number <= 10:
break
print("Not between 1 and 10.")
except ValueError:
print("That's not a number.")
print(f"Thanks, you chose {number}.")Watch out: Never write just
except:without an error name. Then you also catch errors you didn’t expect at all – and you can no longer find typos in your code.
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
try:
number = int("12a")
print("works")
except ValueError:
print("not a number")
print("carry on")Your task
Your turn
Write a calculator that divides two numbers and never crashes. Ask for two numbers with input(). Print Result: 2.5 (for 10 and 4). If an input isn't a number, print Please enter numbers only. If the second number is 0, print Can't divide by 0. Use float() instead of int() so decimals like 2.5 work too.
# Your crash-proof calculator:
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"Result: {a / b}")- Something to think about
Catch the
ZeroDivisionErrorwithexceptZeroDivisionError. - Which command helps?
float("ten")raises aValueError. Catch it withexceptValueError.Both
input()lines have to be inside thetryblock. - Gap code – fill in the ___
try: a = float(input("First number: ")) b = float(input("Second number: ")) print(f"Result: {a / b}") except ValueError: print(___) except ZeroDivisionError: print(___)
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
try:
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"Result: {a / b}")
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("Can't divide by 0.")