Skip to main content

Built-in exceptions

Every exception in Python is an instance of BaseException or a subclass. This page is the canonical hierarchy, with descriptions of where each one is raised. Indentation reflects subclass relationships.

Source-of-record: Objects/exceptions.c, the exception hierarchy.

Base attributes​

All exceptions carry:

AttributeMeaning
argsTuple of arguments passed to the constructor.
__cause__Set by raise ... from ....
__context__Implicit context set when raising during handling.
__traceback__Traceback object (may be set later via with_traceback).
__suppress_context__True after raise ... from None.
__notes__List of strings added via add_note(s) (PEP 678).

Hierarchy​

BaseException
+-- BaseExceptionGroup
+-- GeneratorExit
+-- KeyboardInterrupt
+-- SystemExit
+-- Exception
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ExceptionGroup
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- PythonFinalizationError
| +-- RecursionError
+-- StopAsyncIteration
+-- StopIteration
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- BytesWarning
+-- DeprecationWarning
+-- EncodingWarning
+-- FutureWarning
+-- ImportWarning
+-- PendingDeprecationWarning
+-- ResourceWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UnicodeWarning
+-- UserWarning

BaseException​

The common ancestor. User code should not raise or catch BaseException; it intentionally also catches KeyboardInterrupt, SystemExit, and GeneratorExit.

Direct subclasses of BaseException​

BaseExceptionGroup​

Wraps multiple unrelated exceptions. Constructed as BaseExceptionGroup(message, [exc1, exc2, ...]). Becomes ExceptionGroup if all wrapped exceptions are Exception subclasses.

MethodReturns
.exceptionsTuple of wrapped exceptions.
.messageMessage string.
.subgroup(condition)New group with matching exceptions only.
.split(condition)(matching_group, rest_group); either may be None.

GeneratorExit​

Raised by close() on a generator or coroutine. Allows finally to run. Catching and swallowing it is a RuntimeError.

KeyboardInterrupt​

Raised on SIGINT (Ctrl-C). Default handler is signal.default_int_handler.

SystemExit​

Raised by sys.exit(). The interpreter catches it at the top and exits. Carries .code (the int passed in).

Exception direct subclasses​

ArithmeticError​

Base for OverflowError, ZeroDivisionError, FloatingPointError.

AssertionError​

Raised by assert when the expression is false.

AttributeError​

Raised when attribute lookup fails on a non-mapping (getattr returns or __getattribute__ raises). Carries .name and .obj.

BufferError​

Raised when a buffer-related operation cannot be done.

EOFError​

Raised by input() at end of file.

ExceptionGroup​

Subclass of BaseExceptionGroup whose elements are all Exception.

ImportError​

Raised when import fails. Carries .name and .path. ModuleNotFoundError subclasses it for the specific case of the module not being found.

LookupError​

Base for IndexError, KeyError. Also raised by some codec lookups.

MemoryError​

Raised when memory allocation fails.

NameError​

Raised when a free or global name is unresolved. Carries .name. UnboundLocalError subclasses it for locals.

OSError​

Wraps every OS-level error. Carries .errno, .strerror, .filename, .filename2, .winerror. The errno-specific subclasses below are mapped automatically.

Subclasserrno
BlockingIOErrorEAGAIN, EWOULDBLOCK, EINPROGRESS
ChildProcessErrorECHILD
ConnectionAbortedErrorECONNABORTED
ConnectionRefusedErrorECONNREFUSED
ConnectionResetErrorECONNRESET
BrokenPipeErrorEPIPE, ESHUTDOWN
FileExistsErrorEEXIST
FileNotFoundErrorENOENT
InterruptedErrorEINTR
IsADirectoryErrorEISDIR
NotADirectoryErrorENOTDIR
PermissionErrorEACCES, EPERM
ProcessLookupErrorESRCH
TimeoutErrorETIMEDOUT

ReferenceError​

Raised when a weak reference proxy is used after the referent is garbage-collected.

RuntimeError​

Generic runtime problem. Subclasses:

SubclassRaised when
NotImplementedErrorA method is intentionally not implemented.
RecursionErrorThe recursion limit is exceeded.
PythonFinalizationErrorOperation attempted after interpreter teardown began.

StopIteration​

Raised by __next__ to signal end of iteration. Carries .value (the return value of the generator, when relevant).

StopAsyncIteration​

The async equivalent.

SyntaxError​

Raised during compilation. Carries .msg, .filename, .lineno, .offset, .text, .end_lineno, .end_offset.

SubclassRaised when
IndentationErrorIndentation is malformed.
TabErrorInconsistent tabs and spaces.

SystemError​

Internal interpreter error. Should never happen in user code.

TypeError​

Raised when an operation is applied to an object of inappropriate type.

ValueError​

Raised when an operation receives a value of correct type but inappropriate value.

SubclassRaised when
UnicodeErrorUnicode-related encoding/decoding error.
UnicodeDecodeErrorDecode failure. Has .encoding, .object, .start, .end, .reason.
UnicodeEncodeErrorEncode failure. Same attributes.
UnicodeTranslateErrorTranslate failure.

Warning​

Base for warning categories. Categorisation drives filtering via the warnings module.

SubclassUse
BytesWarningBytes/str confusion.
DeprecationWarningFeature being removed.
EncodingWarningImplicit 'locale' encoding.
FutureWarningBehaviour will change.
ImportWarningProbable import mistake.
PendingDeprecationWarningLong-horizon deprecation.
ResourceWarningResource not explicitly closed.
RuntimeWarningRuntime behaviour suspicious.
SyntaxWarningSuspicious syntax that compiles.
UnicodeWarningUnicode-related warning.
UserWarningGeneric user warning. Default category.

PEP 678 notes​

Every exception supports .add_note(s) to attach a string. Notes are accessible via .__notes__ and rendered in tracebacks.

Exception groups quirks​

Property
BaseExceptionGroup(...) returns an ExceptionGroup if all elements are Exception.
except* must use a non-group exception type; matching the group itself raises TypeError.
subgroup and split preserve __cause__, __context__, and __notes__.

Gopy status​

Class groupState
All BaseException subclassesComplete.
OS errno mappingComplete.
Exception groups (BaseExceptionGroup, ExceptionGroup)Complete.
__notes__ (PEP 678)Complete.
Implicit __context__Complete.

Reference​