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.
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
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
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 Exceptionis the broadest handler you should normally write.SystemExit,KeyboardInterruptandGeneratorExitderive straight fromBaseExceptionso that a catch-all does not swallow Ctrl+C orsys.exit().- Order handlers from specific to general. The first matching
exceptwins; a parent listed before its child hides the child. - A bare
except:catchesBaseExceptiontoo; avoid it. - Families worth knowing:
LookupError(missing key or index),ArithmeticError,OSError(files, sockets; many aliases likeIOError),ImportError,RuntimeError, andWarningfor warnings. - Your own exceptions should subclass
Exceptionor a fitting built-in, such asclass ConfigError(ValueError). - Aliases:
IOError,EnvironmentErrorandWindowsErrorare names forOSError. - Groups:
ExceptionGroup(3.11+) holds several exceptions and is caught withexcept*. - Attributes: every exception has
args,__traceback__,__cause__,__context__, and since 3.11add_note().