Built-in Exceptions — Python 3.13.1 documentation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.

html

__suppress_context__ is false.
3.13.1 Quick search Go 3.13.1 Go

In either case, the exception itself is always shown after any chained exceptions so that the final line of
Built-in Exceptions the traceback always shows the last exception that was raised.

In Python, all exceptions must be instances of a class that derives from BaseException . In a try statement Inheriting from built-in exceptions
with an except clause that mentions a particular class, that clause also handles any exception classes de-
rived from that class (but not exception classes from which it is derived). Two exception classes that are not User code can create subclasses that inherit from an exception type. It’s recommended to only subclass one
related via subclassing are never equivalent, even if they have the same name. exception type at a time to avoid any possible conflicts between how the bases handle the args attribute,
as well as due to possible memory layout incompatibilities.
The built-in exceptions listed in this chapter can be generated by the interpreter or built-in functions. Except
where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a CPython implementation detail: Most built-in exceptions are implemented in C for efficiency, see:
string or a tuple of several items of information (e.g., an error code and a string explaining the code). The Objects/exceptions.c. Some have custom memory layouts which makes it impossible to create a subclass
associated value is usually passed as arguments to the exception class’s constructor. that inherits from multiple exception types. The memory layout of a type is an implementation detail and
might change between Python versions, leading to new conflicts in the future. Therefore, it’s recommended
User code can raise built-in exceptions. This can be used to test an exception handler or to report an error
to avoid subclassing multiple exception types altogether.
condition “just like” the situation in which the interpreter raises the same exception; but beware that there is
nothing to prevent user code from raising an inappropriate error. Base classes

The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to The following exceptions are used mostly as base classes for other exceptions.
derive new exceptions from the Exception class or one of its subclasses, and not from BaseException .
exception BaseException
More information on defining exceptions is available in the Python Tutorial under User-defined Exceptions.
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes
(for that, use Exception ). If str() is called on an instance of this class, the representation of the argu-
Exception context
ment(s) to the instance are returned, or the empty string when there were no arguments.

Three attributes on exception objects provide information about the context in which the exception was args
raised:
The tuple of arguments given to the exception constructor. Some built-in exceptions (like
BaseException.__context__ OSError ) expect a certain number of arguments and assign a special meaning to the elements of
BaseException.__cause__ this tuple, while others are usually called only with a single string giving an error message.
BaseException.__suppress_context__
When raising a new exception while another exception is already being handled, the new exception’s with_traceback(tb)
__context__ attribute is automatically set to the handled exception. An exception may be handled
This method sets tb as the new traceback for the exception and returns the exception object. It
when an except or finally clause, or a with statement, is used.
was more commonly used before the exception chaining features of PEP 3134 became available.

This implicit exception context can be supplemented with an explicit cause by using from with raise : The following example shows how we can convert an instance of SomeException into an instance
of OtherException while preserving the traceback. Once raised, the current frame is pushed onto
raise new_exc from original_exc the traceback of the OtherException , as would have happened to the traceback of the original
SomeException had we allowed it to propagate to the caller.
The expression following from must be an exception or None . It will be set as __cause__ on the raised
exception. Setting __cause__ also implicitly sets the __suppress_context__ attribute to True , so that try:
...
using raise new_exc from None effectively replaces the old exception with the new one for display
except SomeException:
purposes (e.g. converting KeyError to AttributeError ), while leaving the old exception available in tb = sys.exception().__traceback__
__context__ for introspection when debugging. raise OtherException(...).with_traceback(tb)

The default traceback display code shows these chained exceptions in addition to the traceback for the __traceback__
exception itself. An explicitly chained exception in __cause__ is always shown when present. An im- A writable field that holds the traceback object associated with this exception. See also: The raise
plicitly chained exception in __context__ is shown only if __cause__ is None and statement.

1 / 16 6.12.2024 08:142 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

add_note (note) exception FloatingPointError


3.13.1 Go 3.13.1 Go
Not currently used.
Add the string note to the exception’s notes which appear in the standard traceback after the ex-
ception string. A TypeError is raised if note is not a string. exception GeneratorExit
Raised when a generator or coroutine is closed; see generator.close() and coroutine.close() . It
Added in version 3.11.
directly inherits from BaseException instead of Exception since it is technically not an error.
__notes__
exception ImportError
A list of the notes of this exception, which were added with add_note() . This attribute is created Raised when the import statement has troubles trying to load a module. Also raised when the “from
when add_note() is called. list” in from ... import has a name that cannot be found.

Added in version 3.11. The optional name and path keyword-only arguments set the corresponding attributes:
exception Exception
name
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions
The name of the module that was attempted to be imported.
should also be derived from this class.

exception ArithmeticError path

The base class for those built-in exceptions that are raised for various arithmetic errors: The path to any file which triggered the exception.
OverflowError , ZeroDivisionError , FloatingPointError .
Changed in version 3.3: Added the name and path attributes.
exception BufferError
exception ModuleNotFoundError
Raised when a buffer related operation cannot be performed.
A subclass of ImportError which is raised by import when a module could not be located. It is also
exception LookupError raised when None is found in sys.modules .
The base class for the exceptions that are raised when a key or index used on a mapping or sequence
Added in version 3.6.
is invalid: IndexError , KeyError . This can be raised directly by codecs.lookup() .
exception IndexError
Concrete exceptions Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the al-
lowed range; if an index is not an integer, TypeError is raised.)
The following exceptions are the exceptions that are usually raised.
exception KeyError
exception AssertionError
Raised when a mapping (dictionary) key is not found in the set of existing keys.
Raised when an assert statement fails.
exception KeyboardInterrupt
exception AttributeError Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check
Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does for interrupts is made regularly. The exception inherits from BaseException so as to not be acciden-
not support attribute references or attribute assignments at all, TypeError is raised.) tally caught by code that catches Exception and thus prevent the interpreter from exiting.

The name and obj attributes can be set using keyword-only arguments to the constructor. When set
Note: Catching a KeyboardInterrupt requires special consideration. Because it can be raised at
they represent the name of the attribute that was attempted to be accessed and the object that was
unpredictable points, it may, in some circumstances, leave the running program in an inconsistent
accessed for said attribute, respectively.
state. It is generally best to allow KeyboardInterrupt to end the program as quickly as possible or
Changed in version 3.10: Added the name and obj attributes. avoid raising it entirely. (See Note on Signal Handlers and Exceptions.)

exception EOFError
exception MemoryError
Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.:
Raised when an operation runs out of memory but the situation may still be rescued (by deleting some
the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit
objects). The associated value is a string indicating what kind of (internal) operation ran out of memory.
EOF.) Note that because of the underlying memory management architecture (C’s malloc() function), the
interpreter may not always be able to completely recover from this situation; it nevertheless raises an

3 / 16 6.12.2024 08:144 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

exception so that a stack traceback can be printed, in case a run-away program was the cause. functions perror() under POSIX, and FormatMessage() under Windows.
3.13.1 Go 3.13.1 Go
exception NameError filename
Raised when a local or global name is not found. This applies only to unqualified names. The associ- filename2
ated value is an error message that includes the name that could not be found.
For exceptions that involve a file system path (such as open() or os.unlink() ), filename is the
The name attribute can be set using a keyword-only argument to the constructor. When set it represent file name passed to the function. For functions that involve two file system paths (such as
the name of the variable that was attempted to be accessed. os.rename() ), filename2 corresponds to the second file name passed to the function.

Changed in version 3.10: Added the name attribute. Changed in version 3.3: EnvironmentError , IOError , WindowsError , socket.error ,
select.error and mmap.error have been merged into OSError , and the constructor may re-
exception NotImplementedError
turn a subclass.
This exception is derived from RuntimeError . In user defined base classes, abstract methods should
raise this exception when they require derived classes to override the method, or while the class is be- Changed in version 3.4: The filename attribute is now the original file name passed to the func-
ing developed to indicate that the real implementation still needs to be added. tion, instead of the name encoded to or decoded from the filesystem encoding and error handler.
Also, the filename2 constructor argument and attribute was added.
Note: It should not be used to indicate that an operator or method is not meant to be supported
exception OverflowError
at all – in that case either leave the operator / method undefined or, if a subclass, set it to None .
Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for
integers (which would rather raise MemoryError than give up). However, for historical reasons,
Note: NotImplementedError and NotImplemented are not interchangeable, even though they
OverflowError is sometimes raised for integers that are outside a required range. Because of the lack of
have similar names and purposes. See NotImplemented for details on when to use it.
standardization of floating-point exception handling in C, most floating-point operations are not
checked.
exception OSError([arg])
exception OSError(errno, strerror[, filename[, winerror[, filename2]]]) exception PythonFinalizationError
This exception is raised when a system function returns a system-related error, including I/O failures This exception is derived from RuntimeError . It is raised when an operation is blocked during inter-
such as “file not found” or “disk full” (not for illegal argument types or other incidental errors). preter shutdown also known as Python finalization.

The second form of the constructor sets the corresponding attributes, described below. The attributes Examples of operations which can be blocked with a PythonFinalizationError during the Python fi-
default to None if not specified. For backwards compatibility, if three arguments are passed, the args nalization:
attribute contains only a 2-tuple of the first two constructor arguments.
• Creating a new Python thread.
The constructor often actually returns a subclass of OSError , as described in OS exceptions below. The • os.fork() .
particular subclass depends on the final errno value. This behaviour only occurs when constructing
See also the sys.is_finalizing() function.
OSError directly or via an alias, and is not inherited when subclassing.

Added in version 3.13: Previously, a plain RuntimeError was raised.


errno
A numeric error code from the C variable errno . exception RecursionError
This exception is derived from RuntimeError . It is raised when the interpreter detects that the maxi-
winerror mum recursion depth (see sys.getrecursionlimit() ) is exceeded.
Under Windows, this gives you the native Windows error code. The errno attribute is then an ap-
proximate translation, in POSIX terms, of that native error code. Added in version 3.5: Previously, a plain RuntimeError was raised.

exception ReferenceError
Under Windows, if the winerror constructor argument is an integer, the errno attribute is deter-
This exception is raised when a weak reference proxy, created by the weakref.proxy() function, is
mined from the Windows error code, and the errno argument is ignored. On other platforms, the
winerror argument is ignored, and the winerror attribute does not exist. used to access an attribute of the referent after it has been garbage collected. For more information on
weak references, see the weakref module.
strerror
exception RuntimeError
The corresponding error message, as provided by the operating system. It is formatted by the C

5 / 16 6.12.2024 08:146 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is text
3.13.1 Go 3.13.1 Go
a string indicating what precisely went wrong. The source code text involved in the error.

exception StopIteration
end_lineno
Raised by built-in function next() and an iterator's __next__() method to signal that there are no
Which line number in the file the error occurred ends in. This is 1-indexed: the first line in the file
further items produced by the iterator.
has a lineno of 1.
value
end_offset
The exception object has a single attribute value , which is given as an argument when construct-
The column in the end line where the error occurred finishes. This is 1-indexed: the first character
ing the exception, and defaults to None .
in the line has an offset of 1.
When a generator or coroutine function returns, a new StopIteration instance is raised, and the
For errors in f-string fields, the message is prefixed by “f-string: ” and the offsets are offsets in a text
value returned by the function is used as the value parameter to the constructor of the exception.
constructed from the replacement expression. For example, compiling f’Bad {a b} field’ results in this
If a generator code directly or indirectly raises StopIteration , it is converted into a RuntimeError args attribute: (‘f-string: …’, (‘’, 1, 2, ‘(a b)n’, 1, 5)).
(retaining the StopIteration as the new exception’s cause).
Changed in version 3.10: Added the end_lineno and end_offset attributes.

Changed in version 3.3: Added value attribute and the ability for generator functions to use it to exception IndentationError
return a value.
Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError .

Changed in version 3.5: Introduced the RuntimeError transformation via from __future__ exception TabError
import generator_stop , see PEP 479.
Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of
IndentationError .
Changed in version 3.7: Enable PEP 479 for all code by default: a StopIteration error raised in a
generator is transformed into a RuntimeError . exception SystemError

exception StopAsyncIteration Raised when the interpreter finds an internal error, but the situation does not look so serious to cause
it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms).
Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration.
You should report this to the author or maintainer of your Python interpreter. Be sure to report the ver-
Added in version 3.5.
sion of the Python interpreter ( sys.version ; it is also printed at the start of an interactive Python ses-
exception SyntaxError(message, details) sion), the exact error message (the exception’s associated value) and if possible the source of the pro-
Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to gram that triggered the error.
the built-in functions compile() , exec() , or eval() , or when reading the initial script or standard in-
exception SystemExit
put (also interactively).
This exception is raised by the sys.exit() function. It inherits from BaseException instead of
The str() of the exception instance returns only the error message. Details is a tuple whose members Exception so that it is not accidentally caught by code that catches Exception . This allows the excep-
are also available as separate attributes. tion to properly propagate up and cause the interpreter to exit. When it is not handled, the Python in-
terpreter exits; no stack traceback is printed. The constructor accepts the same optional argument
filename passed to sys.exit() . If the value is an integer, it specifies the system exit status (passed to C’s
The name of the file the syntax error occurred in. exit() function); if it is None , the exit status is zero; if it has another type (such as a string), the ob-
ject’s value is printed and the exit status is one.
lineno
Which line number in the file the error occurred in. This is 1-indexed: the first line in the file has a A call to sys.exit() is translated into an exception so that clean-up handlers ( finally clauses of try
lineno of 1. statements) can be executed, and so that a debugger can execute a script without running the risk of
losing control. The os._exit() function can be used if it is absolutely positively necessary to exit im-
offset mediately (for example, in the child process after a call to os.fork() ).
The column in the line where the error occurred. This is 1-indexed: the first character in the line
code
has an offset of 1.

7 / 16 6.12.2024 08:148 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

The exit status or error message that is passed to the constructor. (Defaults to None .) Raised when an operation or function receives an argument that has the right type but an inappropri-
3.13.1 Go 3.13.1 Go
ate value, and the situation is not described by a more precise exception such as IndexError .
exception TypeError
Raised when an operation or function is applied to an object of inappropriate type. The associated exception ZeroDivisionError
value is a string giving details about the type mismatch. Raised when the second argument of a division or modulo operation is zero. The associated value is a
string indicating the type of the operands and the operation.
This exception may be raised by user code to indicate that an attempted operation on an object is not
supported, and is not meant to be. If an object is meant to support a given operation but has not yet The following exceptions are kept for compatibility with previous versions; starting from Python 3.3, they are
provided an implementation, NotImplementedError is the proper exception to raise. aliases of OSError .

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a exception EnvironmentError
TypeError , but passing arguments with the wrong value (e.g. a number outside expected boundaries)
exception IOError
should result in a ValueError .
exception WindowsError
exception UnboundLocalError Only available on Windows.
Raised when a reference is made to a local variable in a function or method, but no value has been
bound to that variable. This is a subclass of NameError . OS exceptions

exception UnicodeError The following exceptions are subclasses of OSError , they get raised depending on the system error code.
Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError .
exception BlockingIOError
UnicodeError has attributes that describe the encoding or decoding error. For example, Raised when an operation would block on an object (e.g. socket) set for non-blocking operation.
err.object[err.start:err.end] gives the particular invalid input that the codec failed on. Corresponds to errno EAGAIN , EALREADY , EWOULDBLOCK and EINPROGRESS .

encoding In addition to those of OSError , BlockingIOError can have one more attribute:
The name of the encoding that raised the error.
characters_written
reason An integer containing the number of characters written to the stream before it blocked. This at-
A string describing the specific codec error. tribute is available when using the buffered I/O classes from the io module.

object exception ChildProcessError


Raised when an operation on a child process failed. Corresponds to errno ECHILD .
The object the codec was attempting to encode or decode.
exception ConnectionError
start
A base class for connection-related issues.
The first index of invalid data in object .
Subclasses are BrokenPipeError , ConnectionAbortedError , ConnectionRefusedError and
end ConnectionResetError .
The index after the last invalid data in object .
exception BrokenPipeError
exception UnicodeEncodeError A subclass of ConnectionError , raised when trying to write on a pipe while the other end has been
Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError . closed, or trying to write on a socket which has been shutdown for writing. Corresponds to errno
EPIPE and ESHUTDOWN .
exception UnicodeDecodeError
Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError . exception ConnectionAbortedError
A subclass of ConnectionError , raised when a connection attempt is aborted by the peer.
exception UnicodeTranslateError
Corresponds to errno ECONNABORTED .
Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError .
exception ConnectionRefusedError
exception ValueError
A subclass of ConnectionError , raised when a connection attempt is refused by the peer.

9 / 16 6.12.2024 08:1410 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

Corresponds to errno ECONNREFUSED . Base class for warning categories.


3.13.1 Go 3.13.1 Go

exception ConnectionResetError exception UserWarning


A subclass of ConnectionError , raised when a connection is reset by the peer. Corresponds to errno Base class for warnings generated by user code.
ECONNRESET .
exception DeprecationWarning
exception FileExistsError Base class for warnings about deprecated features when those warnings are intended for other Python
Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST . developers.

exception FileNotFoundError Ignored by the default warning filters, except in the __main__ module (PEP 565). Enabling the Python
Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT . Development Mode shows this warning.

exception InterruptedError The deprecation policy is described in PEP 387.


Raised when a system call is interrupted by an incoming signal. Corresponds to errno EINTR .
exception PendingDeprecationWarning

Changed in version 3.5: Python now retries system calls when a syscall is interrupted by a signal, Base class for warnings about features which are obsolete and expected to be deprecated in the future,
except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising but are not deprecated at the moment.
InterruptedError .
This class is rarely used as emitting a warning about a possible upcoming deprecation is unusual, and
exception IsADirectoryError DeprecationWarning is preferred for already active deprecations.

Raised when a file operation (such as os.remove() ) is requested on a directory. Corresponds to errno
Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
EISDIR .
The deprecation policy is described in PEP 387.
exception NotADirectoryError
Raised when a directory operation (such as os.listdir() ) is requested on something which is not a exception SyntaxWarning
directory. On most POSIX platforms, it may also be raised if an operation attempts to open or traverse Base class for warnings about dubious syntax.
a non-directory file as if it were a directory. Corresponds to errno ENOTDIR .
exception RuntimeWarning
exception PermissionError Base class for warnings about dubious runtime behavior.
Raised when trying to run an operation without the adequate access rights - for example filesystem
exception FutureWarning
permissions. Corresponds to errno EACCES , EPERM , and ENOTCAPABLE .
Base class for warnings about deprecated features when those warnings are intended for end users of
Changed in version 3.11.1: WASI’s ENOTCAPABLE is now mapped to PermissionError . applications that are written in Python.

exception ProcessLookupError exception ImportWarning

Raised when a given process doesn’t exist. Corresponds to errno ESRCH . Base class for warnings about probable mistakes in module imports.

exception TimeoutError Ignored by the default warning filters. Enabling the Python Development Mode shows this warning.
Raised when a system function timed out at the system level. Corresponds to errno ETIMEDOUT . exception UnicodeWarning
Base class for warnings related to Unicode.
Added in version 3.3: All the above OSError subclasses were added.
exception EncodingWarning
See also: PEP 3151 - Reworking the OS and IO exception hierarchy Base class for warnings related to encodings.

See Opt-in EncodingWarning for details.


Warnings
Added in version 3.10.
The following exceptions are used as warning categories; see the Warning Categories documentation for
more details. exception BytesWarning
Base class for warnings related to bytes and bytearray .
exception Warning

11 / 16 6.12.2024 08:1412 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

exception ResourceWarning and any nested exception groups. If the condition is true for such an exception group, it is in-
3.13.1 Go 3.13.1 Go
Base class for warnings related to resource usage. cluded in the result in full.

Ignored by the default warning filters. Enabling the Python Development Mode shows this warning. Added in version 3.13: condition can be any callable which is not a type object.

Added in version 3.2. split(condition)


Like subgroup() , but returns the pair (match, rest) where match is subgroup(condition) and
Exception groups rest is the remaining non-matching part.

The following are used when it is necessary to raise multiple unrelated exceptions. They are part of the ex- derive(excs)
ception hierarchy so they can be handled with except like all other exceptions. In addition, they are recog-
Returns an exception group with the same message , but which wraps the exceptions in excs .
nised by except* , which matches their subgroups based on the types of the contained exceptions.
This method is used by subgroup() and split() , which are used in various contexts to break up
exception ExceptionGroup(msg, excs)
an exception group. A subclass needs to override it in order to make subgroup() and split()
exception BaseExceptionGroup(msg, excs) return instances of the subclass rather than ExceptionGroup .
Both of these exception types wrap the exceptions in the sequence excs . The msg parameter must be
subgroup() and split() copy the __traceback__ , __cause__ , __context__ and __notes__
a string. The difference between the two classes is that BaseExceptionGroup extends BaseException
and it can wrap any exception, while ExceptionGroup extends Exception and it can only wrap sub- fields from the original exception group to the one returned by derive() , so these fields do not

classes of Exception . This design is so that except Exception catches an ExceptionGroup but not need to be updated by derive() .

BaseExceptionGroup . >>>
>>> class MyGroup(ExceptionGroup):
... def derive(self, excs):
The BaseExceptionGroup constructor returns an ExceptionGroup rather than a BaseExceptionGroup ... return MyGroup(self.message, excs)
if all contained exceptions are Exception instances, so it can be used to make the selection automatic. ...
>>> e = MyGroup("eg", [ValueError(1), TypeError(2)])
The ExceptionGroup constructor, on the other hand, raises a TypeError if any contained exception is >>> e.add_note("a note")
not an Exception subclass. >>> e.__context__ = Exception("context")
>>> e.__cause__ = Exception("cause")
>>> try:
message
... raise e
The msg argument to the constructor. This is a read-only attribute. ... except Exception as e:
... exc = e
...
exceptions
>>> match, rest = exc.split(ValueError)
A tuple of the exceptions in the excs sequence given to the constructor. This is a read-only at- >>> exc, exc.__context__, exc.__cause__, exc.__notes__
(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), [
tribute. >>> match, match.__context__, match.__cause__, match.__notes__
(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note'])
subgroup(condition) >>> rest, rest.__context__, rest.__cause__, rest.__notes__
(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
Returns an exception group that contains only the exceptions from the current group that match >>> exc.__traceback__ is match.__traceback__ is rest.__traceback__
condition, or None if the result is empty. True

The condition can be an exception type or tuple of exception types, in which case each exception Note that BaseExceptionGroup defines __new__() , so subclasses that need a different constructor
is checked for a match using the same check that is used in an except clause. The condition can signature need to override that rather than __init__() . For example, the following defines an excep-
also be a callable (other than a type object) that accepts an exception as its single argument and tion group subclass which accepts an exit_code and and constructs the group’s message from it.
returns true 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 its
message , __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

13 / 16 6.12.2024 08:1414 / 16 6.12.2024 08:14


Built-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.htmlBuilt-in Exceptions — Python 3.13.1 documentation https://docs.python.org/3/library/exceptions.html

class Errors(ExceptionGroup): │ ├── NotImplementedError


3.13.1 Go │ 3.13.1
├── PythonFinalizationError Go
def __new__(cls, errors, exit_code):
self = super().__new__(Errors, f"exit code: {exit_code}", errors) │ └── RecursionError
self.exit_code = exit_code ├── StopAsyncIteration
return self ├── StopIteration
├── SyntaxError
def derive(self, excs): │ └── IndentationError
return Errors(excs, self.exit_code) │ └── TabError
├── SystemError
├── TypeError
Like ExceptionGroup , any subclass of BaseExceptionGroup which is also a subclass of Exception can ├── ValueError
only wrap instances of Exception . │ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
Added in version 3.11. │ └── UnicodeTranslateError
└── Warning
Exception hierarchy ├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
The class hierarchy for built-in exceptions is: ├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
BaseException
├── ResourceWarning
├── BaseExceptionGroup
├── RuntimeWarning
├── GeneratorExit
├── SyntaxWarning
├── KeyboardInterrupt
├── UnicodeWarning
├── SystemExit
└── UserWarning
└── 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

15 / 16 6.12.2024 08:1416 / 16 6.12.2024 08:14

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy