Glossary

Exception Hierarchy

Python's built-in exceptions are organised in a class hierarchy rooted at BaseException. The direct children of BaseException include SystemExit, KeyboardInterrupt, GeneratorExit, and Exception. All "normal" exceptions inherit from Exception, which is why except Exception: catches almost everything without intercepting system-level signals.

The hierarchy enables precise exception handling. except FileNotFoundError: catches only missing files; except OSError: catches FileNotFoundError plus all other OS-related errors (permission denied, directory not found, etc.); except Exception: catches everything except SystemExit, KeyboardInterrupt, and GeneratorExit. This layered structure lets you write handlers at the appropriate level of generality.

Important branches include: OSError (I/O and system errors, with subclasses FileNotFoundError, PermissionError, IsADirectoryError), ValueError (right type but wrong value), TypeError (wrong type), LookupError (parent of KeyError and IndexError), ArithmeticError (parent of ZeroDivisionError and OverflowError), and RuntimeError (generic runtime errors). Custom exception classes should inherit from Exception (or a more specific built-in exception) — never from BaseException directly.

Related terms: Exception, Try/Except

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.