Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

The exception hierarchy

Concept guide to Python's built-in exception hierarchy: BaseException, Exception, the main families such as LookupError and OSError, and catching by parent class.

All Python exceptions are classes arranged in a tree. At the top is BaseException; almost everything you catch lives under Exception. Because except SomeClass also catches every subclass, the tree decides what a handler matches: except LookupError catches both KeyError and IndexError.

Knowing the tree helps you catch the right level of error, write your own exceptions in the right place, and read tracebacks quickly.

TEXT
BaseException
 +-- SystemExit, KeyboardInterrupt, GeneratorExit
 +-- BaseExceptionGroup
 +-- Exception
      +-- ArithmeticError (ZeroDivisionError, OverflowError, FloatingPointError)
      +-- AssertionError, AttributeError, EOFError, MemoryError
      +-- ImportError (ModuleNotFoundError)
      +-- LookupError (IndexError, KeyError)
      +-- NameError (UnboundLocalError)
      +-- OSError (FileNotFoundError, PermissionError, TimeoutError, ...)
      +-- RuntimeError (NotImplementedError, RecursionError)
      +-- StopIteration, StopAsyncIteration
      +-- SyntaxError (IndentationError)
      +-- TypeError, ValueError (UnicodeError)
      +-- Warning (UserWarning, DeprecationWarning, ...)

Exploring the tree

Python Printing the hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Catching by parent class

Python One handler, many errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Key rules

  • except Exception is the broadest handler you should normally write. SystemExit, KeyboardInterrupt and GeneratorExit derive straight from BaseException so that a catch-all does not swallow Ctrl+C or sys.exit().
  • Order handlers from specific to general. The first matching except wins; a parent listed before its child hides the child.
  • A bare except: catches BaseException too; avoid it.
  • Families worth knowing: LookupError (missing key or index), ArithmeticError, OSError (files, sockets; many aliases like IOError), ImportError, RuntimeError, and Warning for warnings.
  • Your own exceptions should subclass Exception or a fitting built-in, such as class ConfigError(ValueError).
  • Aliases: IOError, EnvironmentError and WindowsError are names for OSError.
  • Groups: ExceptionGroup (3.11+) holds several exceptions and is caught with except*.
  • Attributes: every exception has args, __traceback__, __cause__, __context__, and since 3.11 add_note().