Common exception types

Errors & Exceptions, lesson 2 of 6

🛟 Errors & Exceptions, lesson 2 of 6

Common exception types

Meet the errors you'll see most and what usually causes them.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Python has dozens of built-in exceptions, but a handful cause most crashes. Knowing them by name lets you guess the fix from the last line alone:

  • NameError: a name that doesn't exist (a typo, or used before it's defined)
  • TypeError: the wrong type for an operation, like "3" + 4 or len(5)
  • ValueError: right type, bad value: int("hi")
  • IndexError: a list index past the end
  • KeyError: a missing dictionary key
  • ZeroDivisionError: dividing by zero
  • AttributeError: no such method or attribute, like [1, 2].upper()
Example

TypeError: mixing types

Fix it with str(age) or an f-string. Then try len(5) to see a different TypeError message.

Example

ValueError: right type, wrong value

int() accepts a string, but only one that looks like a whole number. Try int("3.5") and int(" 7 ") too.

Quiz

Which exception does this code raise?

Example

Safer alternatives

colors[-1] always gets the last item, and dict.get() returns a default instead of crashing. Only the last line fails.

Quiz

Which exception does this code raise?

Exercise

Crash-proof the shopping list

Each numbered line crashes. Fix all three (without deleting them) so that:

  • last is the last item in items
  • bread_price is the price of bread, or 0 if it has no price
  • summary is the text "Items: 3"