try / except in Python: recover instead of crashing
Some errors you can't prevent — a user types letters where you wanted a number. try / except lets your program catch that and keep running, instead of crashing.
The big idea
try runs risky code; if it raises the error named in except, that handler runs instead of the program crashing.
See it in code
try runs risky code; if it raises the error you name in except, that handler runs instead of the program crashing. Dividing by zero raises ZeroDivisionError — so we catch it:
try:
print(10 / 0)
except ZeroDivisionError:
print("Can't divide by zero!")
print("Still running")Can't divide by zero! Still running
The risky line raised, except caught it, and the program kept going — the Still running line proves it never crashed.
Catch the specific error you expect. int("fifty") raises ValueError, so we name exactly that — bad input is handled, and the program continues:
text = "fifty"
try:
number = int(text)
print("Got:", number)
except ValueError:
print("Not a number:", text)
print("Program continues")Not a number: fifty Program continues
int("fifty") failed, so the try block stopped and the except ValueError ran instead. Naming the exact error keeps real bugs from hiding.
Now wrap that in a reusable function. parse_bet tries the same int(...); if it raises ValueError, the except block runs a safe fallback — returning 0 instead of crashing:
def parse_bet(text):
try:
return int(text)
except ValueError:
print("Not a number:", text)
return 0
print("Bet:", parse_bet("50"))
print("Bet:", parse_bet("fifty"))Bet: 50 Not a number: fifty Bet: 0
parse_bet("50") converted cleanly; parse_bet("fifty") raised ValueError, so the except block caught it, printed a message, and returned a safe 0. The program carried on instead of dying on line one.
Error handling guards every boundary where things can go wrong: parsing user input, reading a file that might be missing (FileNotFoundError), a network request that might time out, a dictionary key that might not exist (KeyError). Catch the specific error you expect, and let the program degrade gracefully.
Try it yourself
Add an except for a different error — wrap data[10] and catch IndexError. Then add an else block (runs when no error occurred) and a finally block (always runs, for cleanup) to see the full shape.
The common mistake
Catching everything with a bare except:. It silently swallows all errors — including typos and bugs you'd want to see — making failures invisible. Always name the specific exception you're prepared to handle, like except ValueError:.
What it unlocks
Handling errors builds on errors and debugging and data types, and makes input safe against whatever the user types.