← Intro to programming with Python
Handling errors with try / except
Plan for things that might go wrong.
Some errors are not your fault: a person types "ten" when you asked for a number, or enters 0 people to split a bill. Instead of crashing, a program can catch the error and respond politely. Put the risky lines inside try:, and what to do if it fails inside except SomeError:. If nothing goes wrong, the except part is skipped. Combined with a loop, you can keep asking until you get a valid answer.
while True:
try:
age = int(input("Your age: "))
break
except ValueError:
print("Please type a whole number, like 15.")
print("Thanks! You are", age)If the person types "fifteen", int() raises a ValueError, the except prints a kind message and the loop asks again. A good answer reaches break and leaves the loop.
Common mistake: a bare except: with no error name. It hides EVERY error, including your own typos, which makes bugs very hard to find. Name the error you expect.
You can catch more than one kind: except (ValueError, ZeroDivisionError):
Only wrap the lines that can actually fail. Keep try blocks small.