Python try and except: how to handle errors
November 4, 2026 · 1 min read
Wrap the risky line in try: and put the recovery in except, naming the error you expect. Python runs the except block instead of crashing.
Retry on bad input, handle a missing file
while True:
try:
quantity = int(input("How many mugs? "))
break
except ValueError:
print("Please type a whole number, like 3.")
try:
with open("orders.txt", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("No orders yet.")
print(f"You ordered {quantity} mugs.")
Run it, type three, press Enter, then type 3 (and no orders.txt exists):
How many mugs? three
Please type a whole number, like 3.
How many mugs? 3
No orders yet.
You ordered 3 mugs.
How it works
int("three")raises aValueError. Python skips the rest of thetryblock and jumps to the matchingexcept ValueError.- If
int()works,breakends the loop. If it fails,breakis skipped, the message prints, and the loop asks again. - Opening a file that doesn't exist raises
FileNotFoundError. The secondexceptcatches it, so the program goes on. - If nothing goes wrong, the
exceptblock is skipped completely.
You can stack several except blocks under one try to handle different errors differently.
Common mistake
Using a bare except: with no name:
try:
quantity = int(input("How many mugs? "))
except:
print("Something went wrong.")
This catches every error, including typos in your own code, and hides what really happened. Name the error instead: except ValueError:.
Also keep the try block short. Put only the lines that might fail inside it, so an except can't accidentally cover a bug elsewhere.
Takeaway
Put risky code in try, handle a specific named error in except, and add a while True: loop with break when you want to ask again.