🎓 A1Learner
🔍

Python Common Exceptions

Common exceptions are the error types Python raises for common mistakes.

TypeError

You mixed types that do not work together.

print("hi" + 5)

ValueError

The type fits, but the value does not.

print(int("abc"))

KeyError

You asked a dictionary for a missing key.

ages = {"Ada": 36}
print(ages["Bob"])

IndexError

You asked for a position that is not there.

colours = ["red", "blue"]
print(colours[5])

ZeroDivisionError

You tried to divide a number by zero.

print(10 / 0)

FileNotFoundError

You tried to open a file that is not there.

open("missing.txt")

NameError

You used a name that was never made.

print(score)

AttributeError

You used a method the value does not have.

number = 5
print(number.upper())

Example

try:
    print(int("abc"))
except ValueError:
    print("ValueError")

try:
    print(10 / 0)
except ZeroDivisionError:
    print("ZeroDivisionError")

try:
    names = ["Ada", "Bob"]
    print(names[9])
except IndexError:
    print("IndexError")

Key points

  • Use the error name to work out the kind of mistake
  • The message after the name gives the detail
  • Most common errors come from keys, indexes, and types
  • A common exception is a named error type that Python raises for a familiar mistake.

In this example, three small traps are set on purpose. The first try turns abc into a number. Its except block prints ValueError. The second try divides ten by zero. Its except block prints ZeroDivisionError. The third try asks a short list for index 9. Its except block prints IndexError. The printed names show the order the traps ran in.

Note

KeyError shows the missing key in quotes.

IndexError means a position, not a key, was wrong.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

A dictionary lookup uses a key that is not there. Which error do you get?