Built-in Exceptions

In Python, all exceptions must be instances of a class that derives fromBaseException. In atry statement with anexceptclause that mentions a particular class, that clause also handles any exceptionclasses derived from that class (but not exception classes from whichit isderived). Two exception classes that are not related via subclassing are neverequivalent, even if they have the same name.

The built-in exceptions listed in this chapter can be generated by the interpreter orbuilt-in functions. Except where mentioned, they have an “associated value”indicating the detailed cause of the error. This may be a string or a tuple ofseveral items of information (e.g., an error code and a string explaining thecode). The associated value is usually passed as arguments to the exceptionclass’s constructor.

User code can raise built-in exceptions. This can be used to test an exceptionhandler or to report an error condition “just like” the situation in which theinterpreter raises the same exception; but beware that there is nothing toprevent user code from raising an inappropriate error.

The built-in exception classes can be subclassed to define new exceptions;programmers are encouraged to derive new exceptions from theExceptionclass or one of its subclasses, and not fromBaseException. Moreinformation on defining exceptions is available in the Python Tutorial underUser-defined Exceptions.

Exception context

Three attributes on exception objects provide information about the context inwhich the exception was raised:

BaseException.__context__
BaseException.__cause__
BaseException.__suppress_context__

When raising a new exception while another exceptionis already being handled, the new exception’s__context__ attribute is automatically set to the handledexception. An exception may be handled when anexcept orfinally clause, or awith statement, is used.

This implicit exception context can besupplemented with an explicit cause by usingfrom withraise:

raisenew_excfromoriginal_exc

The expression followingfrom must be an exception orNone. Itwill be set as__cause__ on the raised exception. Setting__cause__ also implicitly sets the__suppress_context__attribute toTrue, so that usingraisenew_excfromNoneeffectively replaces the old exception with the new one for displaypurposes (e.g. convertingKeyError toAttributeError), whileleaving the old exception available in__context__ for introspectionwhen debugging.

The default traceback display code shows these chained exceptions inaddition to the traceback for the exception itself. An explicitly chainedexception in__cause__ is always shown when present. An implicitlychained exception in__context__ is shown only if__cause__isNone and__suppress_context__ is false.

In either case, the exception itself is always shown after any chainedexceptions so that the final line of the traceback always shows the lastexception that was raised.

Inheriting from built-in exceptions

User code can create subclasses that inherit from an exception type.It’s recommended to only subclass one exception type at a time to avoidany possible conflicts between how the bases handle theargsattribute, as well as due to possible memory layout incompatibilities.

CPython implementation detail: Most built-in exceptions are implemented in C for efficiency, see:Objects/exceptions.c. Some have custom memory layoutswhich makes it impossible to create a subclass that inherits frommultiple exception types. The memory layout of a type is an implementationdetail and might change between Python versions, leading to newconflicts in the future. Therefore, it’s recommended to avoidsubclassing multiple exception types altogether.

Base classes

The following exceptions are used mostly as base classes for other exceptions.

exceptionBaseException

The base class for all built-in exceptions. It is not meant to be directlyinherited by user-defined classes (for that, useException). Ifstr() is called on an instance of this class, the representation ofthe argument(s) to the instance are returned, or the empty string whenthere were no arguments.

args

The tuple of arguments given to the exception constructor. Some built-inexceptions (likeOSError) expect a certain number of arguments andassign a special meaning to the elements of this tuple, while others areusually called only with a single string giving an error message.

with_traceback(tb)

This method setstb as the new traceback for the exception and returnsthe exception object. It was more commonly used before the exceptionchaining features ofPEP 3134 became available. The following exampleshows how we can convert an instance ofSomeException into aninstance ofOtherException while preserving the traceback. Onceraised, the current frame is pushed onto the traceback of theOtherException, as would have happened to the traceback of theoriginalSomeException had we allowed it to propagate to the caller.

try:...exceptSomeException:tb=sys.exception().__traceback__raiseOtherException(...).with_traceback(tb)
__traceback__

A writable field that holds thetraceback object associated with thisexception. See also:The raise statement.

add_note(note)

Add the stringnote to the exception’s notes which appear in the standardtraceback after the exception string. ATypeError is raised ifnoteis not a string.

Added in version 3.11.

__notes__

A list of the notes of this exception, which were added withadd_note().This attribute is created whenadd_note() is called.

Added in version 3.11.

exceptionException

All built-in, non-system-exiting exceptions are derived from this class. Alluser-defined exceptions should also be derived from this class.

exceptionArithmeticError

The base class for those built-in exceptions that are raised for variousarithmetic errors:OverflowError,ZeroDivisionError,FloatingPointError.

exceptionBufferError

Raised when abuffer related operation cannot beperformed.

exceptionLookupError

The base class for the exceptions that are raised when a key or index used ona mapping or sequence is invalid:IndexError,KeyError. Thiscan be raised directly bycodecs.lookup().

Concrete exceptions

The following exceptions are the exceptions that are usually raised.

exceptionAssertionError

Raised when anassert statement fails.

exceptionAttributeError

Raised when an attribute reference (seeAttribute references) orassignment fails. (When an object does not support attribute references orattribute assignments at all,TypeError is raised.)

Thename andobj attributes can be set using keyword-onlyarguments to the constructor. When set they represent the name of the attributethat was attempted to be accessed and the object that was accessed for saidattribute, respectively.

Changed in version 3.10:Added thename andobj attributes.

exceptionEOFError

Raised when theinput() function hits an end-of-file condition (EOF)without reading any data. (N.B.: theio.IOBase.read() andio.IOBase.readline() methods return an empty string when they hit EOF.)

exceptionFloatingPointError

Not currently used.

exceptionGeneratorExit

Raised when agenerator orcoroutine is closed;seegenerator.close() andcoroutine.close(). Itdirectly inherits fromBaseException instead ofException sinceit is technically not an error.

exceptionImportError

Raised when theimport statement has troubles trying toload a module. Also raised when the “from list” infrom...importhas a name that cannot be found.

The optionalname andpath keyword-only argumentsset the corresponding attributes:

name

The name of the module that was attempted to be imported.

path

The path to any file which triggered the exception.

Changed in version 3.3:Added thename andpath attributes.

exceptionModuleNotFoundError

A subclass ofImportError which is raised byimportwhen a module could not be located. It is also raised whenNoneis found insys.modules.

Added in version 3.6.

exceptionIndexError

Raised when a sequence subscript is out of range. (Slice indices aresilently truncated to fall in the allowed range; if an index is not aninteger,TypeError is raised.)

exceptionKeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

exceptionKeyboardInterrupt

Raised when the user hits the interrupt key (normallyControl-C orDelete). During execution, a check for interrupts is maderegularly. The exception inherits fromBaseException so as to not beaccidentally caught by code that catchesException and thus preventthe interpreter from exiting.

Note

Catching aKeyboardInterrupt requires special consideration.Because it can be raised at unpredictable points, it may, in somecircumstances, leave the running program in an inconsistent state. It isgenerally best to allowKeyboardInterrupt to end the program asquickly as possible or avoid raising it entirely. (SeeNote on Signal Handlers and Exceptions.)

exceptionMemoryError

Raised when an operation runs out of memory but the situation may still berescued (by deleting some objects). The associated value is a string indicatingwhat kind of (internal) operation ran out of memory. Note that because of theunderlying memory management architecture (C’smalloc() function), theinterpreter may not always be able to completely recover from this situation; itnevertheless raises an exception so that a stack traceback can be printed, incase a run-away program was the cause.

exceptionNameError

Raised when a local or global name is not found. This applies only tounqualified names. The associated value is an error message that includes thename that could not be found.

Thename attribute can be set using a keyword-only argument to theconstructor. When set it represent the name of the variable that was attemptedto be accessed.

Changed in version 3.10:Added thename attribute.

exceptionNotImplementedError

This exception is derived fromRuntimeError. In user defined baseclasses, abstract methods should raise this exception when they requirederived classes to override the method, or while the class is beingdeveloped to indicate that the real implementation still needs to be added.

Note

It should not be used to indicate that an operator or method is notmeant to be supported at all – in that case either leave the operator /method undefined or, if a subclass, set it toNone.

Caution

NotImplementedError andNotImplemented are notinterchangeable. This exception should only be used as describedabove; seeNotImplemented for details on correct usage ofthe built-in constant.

exceptionOSError([arg])
exceptionOSError(errno,strerror[,filename[,winerror[,filename2]]])

This exception is raised when a system function returns a system-relatederror, including I/O failures such as “file not found” or “disk full”(not for illegal argument types or other incidental errors).

The second form of the constructor sets the corresponding attributes,described below. The attributes default toNone if notspecified. For backwards compatibility, if three arguments are passed,theargs attribute contains only a 2-tupleof the first two constructor arguments.

The constructor often actually returns a subclass ofOSError, asdescribed inOS exceptions below. The particular subclass depends onthe finalerrno value. This behaviour only occurs whenconstructingOSError directly or via an alias, and is notinherited when subclassing.

errno

A numeric error code from the C variableerrno.

winerror

Under Windows, this gives you the nativeWindows error code. Theerrno attribute is then an approximatetranslation, in POSIX terms, of that native error code.

Under Windows, if thewinerror constructor argument is an integer,theerrno attribute is determined from the Windows error code,and theerrno argument is ignored. On other platforms, thewinerror argument is ignored, and thewinerror attributedoes not exist.

strerror

The corresponding error message, as provided bythe operating system. It is formatted by the Cfunctionsperror() under POSIX, andFormatMessage()under Windows.

filename
filename2

For exceptions that involve a file system path (such asopen() oros.unlink()),filename is the file name passed to the function.For functions that involve two file system paths (such asos.rename()),filename2 corresponds to the secondfile name passed to the function.

Changed in version 3.3:EnvironmentError,IOError,WindowsError,socket.error,select.error andmmap.error have been merged intoOSError, and theconstructor may return a subclass.

Changed in version 3.4:Thefilename attribute is now the original file name passed tothe function, instead of the name encoded to or decoded from thefilesystem encoding and error handler. Also, thefilename2constructor argument and attribute was added.

exceptionOverflowError

Raised when the result of an arithmetic operation is too large to berepresented. This cannot occur for integers (which would rather raiseMemoryError than give up). However, for historical reasons,OverflowError is sometimes raised for integers that are outside a requiredrange. Because of the lack of standardization of floating-point exceptionhandling in C, most floating-point operations are not checked.

exceptionPythonFinalizationError

This exception is derived fromRuntimeError. It is raised whenan operation is blocked during interpreter shutdown also known asPython finalization.

Examples of operations which can be blocked with aPythonFinalizationError during the Python finalization:

See also thesys.is_finalizing() function.

Added in version 3.13:Previously, a plainRuntimeError was raised.

exceptionRecursionError

This exception is derived fromRuntimeError. It is raised when theinterpreter detects that the maximum recursion depth (seesys.getrecursionlimit()) is exceeded.

Added in version 3.5:Previously, a plainRuntimeError was raised.

exceptionReferenceError

This exception is raised when a weak reference proxy, created by theweakref.proxy() function, is used to access an attribute of the referentafter it has been garbage collected. For more information on weak references,see theweakref module.

exceptionRuntimeError

Raised when an error is detected that doesn’t fall in any of the othercategories. The associated value is a string indicating what precisely wentwrong.

exceptionStopIteration

Raised by built-in functionnext() and aniterator's__next__() method to signal that there are no furtheritems produced by the iterator.

value

The exception object has a single attributevalue, which isgiven as an argument when constructing the exception, and defaultstoNone.

When agenerator orcoroutine functionreturns, a newStopIteration instance israised, and the value returned by the function is used as thevalue parameter to the constructor of the exception.

If a generator code directly or indirectly raisesStopIteration,it is converted into aRuntimeError (retaining theStopIteration as the new exception’s cause).

Changed in version 3.3:Addedvalue attribute and the ability for generator functions touse it to return a value.

Changed in version 3.5:Introduced the RuntimeError transformation viafrom__future__importgenerator_stop, seePEP 479.

Changed in version 3.7:EnablePEP 479 for all code by default: aStopIterationerror raised in a generator is transformed into aRuntimeError.

exceptionStopAsyncIteration

Must be raised by__anext__() method of anasynchronous iterator object to stop the iteration.

Added in version 3.5.

exceptionSyntaxError(message,details)

Raised when the parser encounters a syntax error. This may occur in animport statement, in a call to the built-in functionscompile(),exec(),oreval(), or when reading the initial script or standard input(also interactively).

Thestr() of the exception instance returns only the error message.Details is a tuple whose members are also available as separate attributes.

filename

The name of the file the syntax error occurred in.

lineno

Which line number in the file the error occurred in. This is1-indexed: the first line in the file has alineno of 1.

offset

The column in the line where the error occurred. This is1-indexed: the first character in the line has anoffset of 1.

text

The source code text involved in the error.

end_lineno

Which line number in the file the error occurred ends in. This is1-indexed: the first line in the file has alineno of 1.

end_offset

The column in the end line where the error occurred finishes. This is1-indexed: the first character in the line has anoffset of 1.

For errors in f-string fields, the message is prefixed by “f-string: ”and the offsets are offsets in a text constructed from the replacementexpression. For example, compiling f’Bad {a b} field’ results in thisargs attribute: (‘f-string: …’, (‘’, 1, 2, ‘(a b)n’, 1, 5)).

Changed in version 3.10:Added theend_lineno andend_offset attributes.

exceptionIndentationError

Base class for syntax errors related to incorrect indentation. This is asubclass ofSyntaxError.

exceptionTabError

Raised when indentation contains an inconsistent use of tabs and spaces.This is a subclass ofIndentationError.

exceptionSystemError

Raised when the interpreter finds an internal error, but the situation does notlook so serious to cause it to abandon all hope. The associated value is astring indicating what went wrong (in low-level terms). InCPython,this could be raised by incorrectly using Python’s C API, such as returningaNULL value without an exception set.

If you’re confident that this exception wasn’t your fault, or the fault ofa package you’re using, you should report this to the author or maintainerof your Python interpreter.Be sure to report the version of the Python interpreter (sys.version; it isalso printed at the start of an interactive Python session), the exact errormessage (the exception’s associated value) and if possible the source of theprogram that triggered the error.

exceptionSystemExit

This exception is raised by thesys.exit() function. It inherits fromBaseException instead ofException so that it is not accidentallycaught by code that catchesException. This allows the exception toproperly propagate up and cause the interpreter to exit. When it is nothandled, the Python interpreter exits; no stack traceback is printed. Theconstructor accepts the same optional argument passed tosys.exit().If the value is an integer, it specifies the system exit status (passed toC’sexit() function); if it isNone, the exit status is zero; ifit has another type (such as a string), the object’s value is printed andthe exit status is one.

A call tosys.exit() is translated into an exception so that clean-uphandlers (finally clauses oftry statements) can beexecuted, and so that a debugger can execute a script without running the riskof losing control. Theos._exit() function can be used if it isabsolutely positively necessary to exit immediately (for example, in the childprocess after a call toos.fork()).

code

The exit status or error message that is passed to the constructor.(Defaults toNone.)

exceptionTypeError

Raised when an operation or function is applied to an object of inappropriatetype. The associated value is a string giving details about the type mismatch.

This exception may be raised by user code to indicate that an attemptedoperation on an object is not supported, and is not meant to be. If an objectis meant to support a given operation but has not yet provided animplementation,NotImplementedError is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing alist when anint is expected) should result in aTypeError, but passingarguments with the wrong value (e.g. a number outside expected boundaries)should result in aValueError.

exceptionUnboundLocalError

Raised when a reference is made to a local variable in a function or method, butno value has been bound to that variable. This is a subclass ofNameError.

exceptionUnicodeError

Raised when a Unicode-related encoding or decoding error occurs. It is asubclass ofValueError.

UnicodeError has attributes that describe the encoding or decodingerror. For example,err.object[err.start:err.end] gives the particularinvalid input that the codec failed on.

encoding

The name of the encoding that raised the error.

reason

A string describing the specific codec error.

object

The object the codec was attempting to encode or decode.

start

The first index of invalid data inobject.

end

The index after the last invalid data inobject.

exceptionUnicodeEncodeError

Raised when a Unicode-related error occurs during encoding. It is a subclass ofUnicodeError.

exceptionUnicodeDecodeError

Raised when a Unicode-related error occurs during decoding. It is a subclass ofUnicodeError.

exceptionUnicodeTranslateError

Raised when a Unicode-related error occurs during translating. It is a subclassofUnicodeError.

exceptionValueError

Raised when an operation or function receives an argument that has theright type but an inappropriate value, and the situation is not described by amore precise exception such asIndexError.

exceptionZeroDivisionError

Raised when the second argument of a division or modulo operation is zero. Theassociated value is a string indicating the type of the operands and theoperation.

The following exceptions are kept for compatibility with previous versions;starting from Python 3.3, they are aliases ofOSError.

exceptionEnvironmentError
exceptionIOError
exceptionWindowsError

Only available on Windows.

OS exceptions

The following exceptions are subclasses ofOSError, they get raiseddepending on the system error code.

exceptionBlockingIOError

Raised when an operation would block on an object (e.g. socket) setfor non-blocking operation.Corresponds toerrnoEAGAIN,EALREADY,EWOULDBLOCK andEINPROGRESS.

In addition to those ofOSError,BlockingIOError can haveone more attribute:

characters_written

An integer containing the number of characters written to the streambefore it blocked. This attribute is available when using thebuffered I/O classes from theio module.

exceptionChildProcessError

Raised when an operation on a child process failed.Corresponds toerrnoECHILD.

exceptionConnectionError

A base class for connection-related issues.

Subclasses areBrokenPipeError,ConnectionAbortedError,ConnectionRefusedError andConnectionResetError.

exceptionBrokenPipeError

A subclass ofConnectionError, raised when trying to write on apipe while the other end has been closed, or trying to write on a socketwhich has been shutdown for writing.Corresponds toerrnoEPIPE andESHUTDOWN.

exceptionConnectionAbortedError

A subclass ofConnectionError, raised when a connection attemptis aborted by the peer.Corresponds toerrnoECONNABORTED.

exceptionConnectionRefusedError

A subclass ofConnectionError, raised when a connection attemptis refused by the peer.Corresponds toerrnoECONNREFUSED.

exceptionConnectionResetError

A subclass ofConnectionError, raised when a connection isreset by the peer.Corresponds toerrnoECONNRESET.

exceptionFileExistsError

Raised when trying to create a file or directory which already exists.Corresponds toerrnoEEXIST.

exceptionFileNotFoundError

Raised when a file or directory is requested but doesn’t exist.Corresponds toerrnoENOENT.

exceptionInterruptedError

Raised when a system call is interrupted by an incoming signal.Corresponds toerrnoEINTR.

Changed in version 3.5:Python now retries system calls when a syscall is interrupted by asignal, except if the signal handler raises an exception (seePEP 475for the rationale), instead of raisingInterruptedError.

exceptionIsADirectoryError

Raised when a file operation (such asos.remove()) is requestedon a directory.Corresponds toerrnoEISDIR.

exceptionNotADirectoryError

Raised when a directory operation (such asos.listdir()) is requested onsomething which is not a directory. On most POSIX platforms, it may also beraised if an operation attempts to open or traverse a non-directory file as ifit were a directory.Corresponds toerrnoENOTDIR.

exceptionPermissionError

Raised when trying to run an operation without the adequate accessrights - for example filesystem permissions.Corresponds toerrnoEACCES,EPERM, andENOTCAPABLE.

Changed in version 3.11.1:WASI’sENOTCAPABLE is now mapped toPermissionError.

exceptionProcessLookupError

Raised when a given process doesn’t exist.Corresponds toerrnoESRCH.

exceptionTimeoutError

Raised when a system function timed out at the system level.Corresponds toerrnoETIMEDOUT.

Added in version 3.3:All the aboveOSError subclasses were added.

See also

PEP 3151 - Reworking the OS and IO exception hierarchy

Warnings

The following exceptions are used as warning categories; see theWarning Categories documentation for more details.

exceptionWarning

Base class for warning categories.

exceptionUserWarning

Base class for warnings generated by user code.

exceptionDeprecationWarning

Base class for warnings about deprecated features when those warnings areintended for other Python developers.

Ignored by the default warning filters, except in the__main__ module(PEP 565). Enabling thePython Development Mode showsthis warning.

The deprecation policy is described inPEP 387.

exceptionPendingDeprecationWarning

Base class for warnings about features which are obsolete andexpected to be deprecated in the future, but are not deprecatedat the moment.

This class is rarely used as emitting a warning about a possibleupcoming deprecation is unusual, andDeprecationWarningis preferred for already active deprecations.

Ignored by the default warning filters. Enabling thePythonDevelopment Mode shows this warning.

The deprecation policy is described inPEP 387.

exceptionSyntaxWarning

Base class for warnings about dubious syntax.

exceptionRuntimeWarning

Base class for warnings about dubious runtime behavior.

exceptionFutureWarning

Base class for warnings about deprecated features when those warnings areintended for end users of applications that are written in Python.

exceptionImportWarning

Base class for warnings about probable mistakes in module imports.

Ignored by the default warning filters. Enabling thePythonDevelopment Mode shows this warning.

exceptionUnicodeWarning

Base class for warnings related to Unicode.

exceptionEncodingWarning

Base class for warnings related to encodings.

SeeOpt-in EncodingWarning for details.

Added in version 3.10.

exceptionBytesWarning

Base class for warnings related tobytes andbytearray.

exceptionResourceWarning

Base class for warnings related to resource usage.

Ignored by the default warning filters. Enabling thePythonDevelopment Mode shows this warning.

Added in version 3.2.

Exception groups

The following are used when it is necessary to raise multiple unrelatedexceptions. They are part of the exception hierarchy so they can behandled withexcept like all other exceptions. In addition,they are recognised byexcept*, which matchestheir subgroups based on the types of the contained exceptions.

exceptionExceptionGroup(msg,excs)
exceptionBaseExceptionGroup(msg,excs)

Both of these exception types wrap the exceptions in the sequenceexcs.Themsg parameter must be a string. The difference between the twoclasses is thatBaseExceptionGroup extendsBaseException andit can wrap any exception, whileExceptionGroup extendsExceptionand it can only wrap subclasses ofException. This design is so thatexceptException catches anExceptionGroup but notBaseExceptionGroup.

TheBaseExceptionGroup constructor returns anExceptionGrouprather than aBaseExceptionGroup if all contained exceptions areException instances, so it can be used to make the selectionautomatic. TheExceptionGroup constructor, on the other hand,raises aTypeError if any contained exception is not anException subclass.

message

Themsg argument to the constructor. This is a read-only attribute.

exceptions

A tuple of the exceptions in theexcs sequence given to theconstructor. This is a read-only attribute.

subgroup(condition)

Returns an exception group that contains only the exceptions from thecurrent group that matchcondition, orNone if the result is empty.

The condition can be an exception type or tuple of exception types, in whichcase each exception is checked for a match using the same check that is usedin anexcept clause. The condition can also be a callable (other thana type object) that accepts an exception as its single argument and returnstrue for the exceptions that should be in the subgroup.

The nesting structure of the current exception is preserved in the result,as are the values of itsmessage,__traceback__,__cause__,__context__ and__notes__ fields.Empty nested groups are omitted from the result.

The condition is checked for all exceptions in the nested exception group,including the top-level and any nested exception groups. If the condition istrue for such an exception group, it is included in the result in full.

Added in version 3.13:condition can be any callable which is not a type object.

split(condition)

Likesubgroup(), but returns the pair(match,rest) wherematchissubgroup(condition) andrest is the remaining non-matchingpart.

derive(excs)

Returns an exception group with the samemessage, but whichwraps the exceptions inexcs.

This method is used bysubgroup() andsplit(), whichare used in various contexts to break up an exception group. Asubclass needs to override it in order to makesubgroup()andsplit() return instances of the subclass ratherthanExceptionGroup.

subgroup() andsplit() copy the__traceback__,__cause__,__context__ and__notes__ fields fromthe original exception group to the one returned byderive(), sothese fields do not need to be updated byderive().

>>>classMyGroup(ExceptionGroup):...defderive(self,excs):...returnMyGroup(self.message,excs)...>>>e=MyGroup("eg",[ValueError(1),TypeError(2)])>>>e.add_note("a note")>>>e.__context__=Exception("context")>>>e.__cause__=Exception("cause")>>>try:...raisee...exceptExceptionase:...exc=e...>>>match,rest=exc.split(ValueError)>>>exc,exc.__context__,exc.__cause__,exc.__notes__(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])>>>match,match.__context__,match.__cause__,match.__notes__(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note'])>>>rest,rest.__context__,rest.__cause__,rest.__notes__(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])>>>exc.__traceback__ismatch.__traceback__isrest.__traceback__True

Note thatBaseExceptionGroup defines__new__(), sosubclasses that need a different constructor signature need tooverride that rather than__init__(). For example, the followingdefines an exception group subclass which accepts an exit_code andand constructs the group’s message from it.

classErrors(ExceptionGroup):def__new__(cls,errors,exit_code):self=super().__new__(Errors,f"exit code:{exit_code}",errors)self.exit_code=exit_codereturnselfdefderive(self,excs):returnErrors(excs,self.exit_code)

LikeExceptionGroup, any subclass ofBaseExceptionGroup whichis also a subclass ofException can only wrap instances ofException.

Added in version 3.11.

Exception hierarchy

The class hierarchy for built-in exceptions is:

BaseException ├── BaseExceptionGroup ├── GeneratorExit ├── KeyboardInterrupt ├── SystemExit └── Exception      ├── ArithmeticError      │    ├── FloatingPointError      │    ├── OverflowError      │    └── ZeroDivisionError      ├── AssertionError      ├── AttributeError      ├── BufferError      ├── EOFError      ├── ExceptionGroup [BaseExceptionGroup]      ├── 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