Codiqo

Learn Python · lesson 38 of 60 · about 9 minutes

try and except

Work out how many weeks to the bike: catch errors so your program can recover instead of crashing.

What you'll learn

  • Wrap risky code in try
  • Handle specific errors with except
  • Use else and finally

Weeks to the bike

Sam types how much they can save each week, and the assistant works out how many weeks are left until the bike, rounding up with math.ceil. Two things can go wrong: a typed answer that isn't a whole number makes int() raise a ValueError, and an answer of 0 makes the division raise a ZeroDivisionError. Both lines go inside try, each problem gets its own except with its own message, and else prints the answer only when nothing went wrong.

Plan for things going wrong

Put code that might fail inside try. If an error happens, Python jumps to the matching except block instead of crashing.

Catch specific errors, like except ValueError, so you don't accidentally hide bugs you didn't expect.

Safe number input

text = input("Age: ")
try:
    age = int(text)
    print("Next year:", age + 1)
except ValueError:
    print("That's not a number")

Output

Age: That's not a number

else and finally

else runs only if nothing went wrong. finally runs every time, error or not, which is handy for tidying up.

All four parts

for d in [2, 0]:
    try:
        r = 10 / d
    except ZeroDivisionError:
        print("can't divide by 0")
    else:
        print("result", r)
    finally:
        print("done")

Output

result 5.0
done
can't divide by 0
done

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.