Module 4 · Exceptions · Lesson 4 of 6
Exceptions you'll meet
Python has dozens of built-in exception types, but a handful show up again and again. Recognising them on sight turns a scary traceback into a quick diagnosis — you read the name and you already know roughly what happened.
The ones you'll meet most
ZeroDivisionError
10 / 0
dividing by zero
ValueError
int("abc")
right type, impossible value
TypeError
"3" + 5
wrong type for the operation
AttributeError
[1].depend(2)
no such method/attribute
- ZeroDivisionError — any division by zero, with /, // or %.
- ValueError — the right type but an impossible value, like int("abc").
- TypeError — the wrong type for the operation, like adding a string to a number.
- AttributeError — asking for a method or attribute a value doesn't have.
You can capture the exception object itself with except ... as e, which is handy for printing its message. Run this to see four different exceptions, each caught and named:
Run it yourselfruns in your browser · Python
main.py
Notice the single except Exception caught all four. That's because these specific errors are all kinds of Exception — so catching the general type catches the specific ones too. (One to leave alone: SyntaxError means your code itself is malformed — fix it, don't catch it.)