Part 06 / Topic 3 of 10
Common built-in exceptions
Each exception has a type (its name) that tells you what kind of problem happened.
Real-world example: the mistakes a canteen billing app could make.
| Exception | When it happens | Example |
|---|---|---|
ValueError |
Right type, wrong value | int("abc") |
TypeError |
Wrong type for the operation | "Age: " + 25 |
KeyError |
Dict key not found | prices["mango"] |
IndexError |
List index out of range | [1, 2][5] |
ZeroDivisionError |
Division by zero | 10 / 0 |
FileNotFoundError |
File does not exist | open("missing.txt") |
AttributeError |
Object has no such attribute/method | "hi".push("!") |
NameError |
Name not defined (often a typo) | print(totl) |
(open() reads files; you will learn it in Part 8.) See all of them run in examples/01_common_exceptions.py.
๐ Going deeper: exceptions form a family tree.
KeyErrorandIndexErrorare both kinds ofLookupError, and almost all of them are kinds ofException.Ctrl+C(KeyboardInterrupt) andSystemExitsit outsideException, underBaseException. That is whyexcept Exception:does not block Ctrl+C, but a bareexcept:does.
Read more: the full list, in the official built-in exceptions reference.
Done here? The practice set for Part 6 โ 7 exercises with solutions โ is on the part page.