Learning LibraryCore Coding LibraryTeens

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

1The basics

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:

python
try:
    print(10 / 0)
except ZeroDivisionError:
    print("Can't divide by zero!")

print("Still running")
Run it — the error is caught, not fatal:
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.

2A step further

Catch the specific error you expect. int("fifty") raises ValueError, so we name exactly that — bad input is handled, and the program continues:

python
text = "fifty"
try:
    number = int(text)
    print("Got:", number)
except ValueError:
    print("Not a number:", text)

print("Program continues")
Run it — the conversion fails, but the program survives:
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.

3In our world

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:

python
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"))
Run it — the bad input is caught, not crashed on:
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.

The same idea, everywhere

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.