7. Handling Errors

Every programmer’s code breaks. A lot. When it does, Python shows you a red error message. This page teaches you not to panic — and how to handle errors on purpose so your program doesn’t just crash.

In some other languages this is called “try / catch”. In Python we say try / except — same idea, different word.


Reading an error message

When your code hits a problem it can’t get past, it crashes and prints an error. Here’s an example. This code tries to turn the word “hello” into a number, which is impossible:

number_of_creatures = int("hello")

Output:

Traceback (most recent call last):
  File "my_program.py", line 1, in <module>
    number_of_creatures = int("hello")
ValueError: invalid literal for int() with base 10: 'hello'

Don’t be scared by all that text! Read it from the bottom up:

  • The last line tells you the kind of error: ValueError. That’s the most useful bit.
  • Just above, it shows you the line of code that broke.
  • The message explains why: you can’t turn 'hello' into a number.

Nine times out of ten, reading that bottom line tells you what went wrong.

A few errors you’ll meet a lot

  • NameError — you used a variable name that doesn’t exist (maybe a typo?).
  • TypeError — you tried to mix things that don’t go together, like adding a number to text.
  • ValueError — a value was the wrong kind, like int("hello").
  • IndexError — you asked for a list position that isn’t there, like item 10 in a list of 3.
  • IndentationError — your spacing is wrong (remember the 4-space indent!).

Handling errors on purpose: try / except

Sometimes you know something might go wrong, and you don’t want the whole program to crash. You want to say: “try this, but if it goes wrong, do this instead.”

That’s try / except.

try:
    number_of_creatures = int("hello")
    print(f"We have {number_of_creatures} creatures.")
except ValueError:
    print("That wasn't a number! Using 1 creature instead.")
    number_of_creatures = 1

print(f"Continuing with {number_of_creatures} creatures.")

Output:

That wasn't a number! Using 1 creature instead.
Continuing with 1 creature.

See how the program didn’t crash? The try part failed, so Python jumped to the except part, sorted things out, and carried on.

  • Everything you want to attempt goes under try:.
  • What to do if it goes wrong goes under except:.

A friendly real example: asking for a number

input() gives you text. If you try to turn it into a number and the person typed something silly, it crashes. try / except makes it polite instead:

try:
    answer = input("How many creatures should we start with? ")
    creature_count = int(answer)
    print(f"Great — starting with {creature_count} creatures!")
except ValueError:
    print("Hmm, that wasn't a whole number. I'll start with 10 instead.")
    creature_count = 10

If the person types 5, it works. If they type banana, it doesn’t crash — it just uses 10.


Catching a specific error

Notice we wrote except ValueError: — not just except:. It’s good manners (and safer) to say which error you expect. That way you only catch the problem you were ready for, and other, surprising errors still show up so you can find real bugs.

creature_energies = [100, 75, 40]

try:
    print(creature_energies[10])     # there is no item 10!
except IndexError:
    print("There's no creature at that position.")

Output:

There's no creature at that position.

finally — do this no matter what (optional, for later)

Sometimes you want a bit of code to run whether or not there was an error — like tidying up. That’s finally. You won’t need this much at first, but here it is so you recognise it:

try:
    print("Trying something risky...")
    result = 10 / 0          # dividing by zero is not allowed!
except ZeroDivisionError:
    print("Oops, can't divide by zero.")
finally:
    print("This always runs, error or not.")

Output:

Trying something risky...
Oops, can't divide by zero.
This always runs, error or not.

The most important message on this page

Errors are not you failing. Errors are the computer helping you. They point at the exact line and tell you what’s wrong. Read the bottom line, find the line number, and fix it. That’s the whole job. You’ll get fast at it. 💪


✅ Quick recap

  • A crash prints an error — read the bottom line first for the kind of error.
  • Put risky code under try: and the backup plan under except SomeError:.
  • Name the error you expect (like ValueError) rather than catching everything.
  • finally: runs whether or not there was an error.
  • Errors are normal and helpful — they tell you exactly where to look.