SyntaxStudy
Sign Up
Python Built-in Exception Hierarchy
Python Intermediate 4 min read

Built-in Exception Hierarchy

Built-in Exception Hierarchy

Python exceptions form a class hierarchy. BaseException is the root; Exception is the base for most errors. Knowing the hierarchy helps you catch at the right level.

Example
# Common hierarchy:
# BaseException
#   SystemExit, KeyboardInterrupt, GeneratorExit
#   Exception
#     ValueError, TypeError, KeyError, IndexError ...

try:
    raise KeyError("missing")
except LookupError:   # parent of KeyError
    print("Lookup problem")
Pro Tip

Catch LookupError to handle both KeyError and IndexError.