| 1 |
.. _bltin-exceptions: |
| 2 |
|
| 3 |
Built-in Exceptions |
| 4 |
=================== |
| 5 |
|
| 6 |
.. index:: |
| 7 |
pair: statement; try |
| 8 |
pair: statement; except |
| 9 |
|
| 10 |
In Python, all exceptions must be instances of a class that derives from |
| 11 |
:class:`BaseException`. In a :keyword:`try` statement with an :keyword:`except` |
| 12 |
clause that mentions a particular class, that clause also handles any exception |
| 13 |
classes derived from that class (but not exception classes from which *it* is |
| 14 |
derived). Two exception classes that are not related via subclassing are never |
| 15 |
equivalent, even if they have the same name. |
| 16 |
|
| 17 |
.. index:: pair: statement; raise |
| 18 |
|
| 19 |
The built-in exceptions listed in this chapter can be generated by the interpreter or |
| 20 |
built-in functions. Except where mentioned, they have an "associated value" |
| 21 |
indicating the detailed cause of the error. This may be a string or a tuple of |
| 22 |
several items of information (e.g., an error code and a string explaining the |
| 23 |
code). The associated value is usually passed as arguments to the exception |
| 24 |
class's constructor. |
| 25 |
|
| 26 |
User code can raise built-in exceptions. This can be used to test an exception |
| 27 |
handler or to report an error condition "just like" the situation in which the |
| 28 |
interpreter raises the same exception; but beware that there is nothing to |
| 29 |
prevent user code from raising an inappropriate error. |
| 30 |
|
| 31 |
The built-in exception classes can be subclassed to define new exceptions; |
| 32 |
programmers are encouraged to derive new exceptions from the :exc:`Exception` |
| 33 |
class or one of its subclasses, and not from :exc:`BaseException`. More |
| 34 |
information on defining exceptions is available in the Python Tutorial under |
| 35 |
:ref:`tut-userexceptions`. |
| 36 |
|
| 37 |
|
| 38 |
Exception context |
| 39 |
----------------- |
| 40 |
|
| 41 |
.. index:: pair: exception; chaining |
| 42 |
__cause__ (exception attribute) |
| 43 |
__context__ (exception attribute) |
| 44 |
__suppress_context__ (exception attribute) |
| 45 |
|
| 46 |
Three attributes on exception objects provide information about the context in |
| 47 |
which the exception was raised: |
| 48 |
|
| 49 |
.. attribute:: BaseException.__context__ |
| 50 |
BaseException.__cause__ |
| 51 |
BaseException.__suppress_context__ |
| 52 |
|
| 53 |
When raising a new exception while another exception |
| 54 |
is already being handled, the new exception's |
| 55 |
:attr:`!__context__` attribute is automatically set to the handled |
| 56 |
exception. An exception may be handled when an :keyword:`except` or |
| 57 |
:keyword:`finally` clause, or a :keyword:`with` statement, is used. |
| 58 |
|
| 59 |
This implicit exception context can be |
| 60 |
supplemented with an explicit cause by using :keyword:`!from` with |
| 61 |
:keyword:`raise`:: |
| 62 |
|
| 63 |
raise new_exc from original_exc |
| 64 |
|
| 65 |
The expression following :keyword:`from<raise>` must be an exception or ``None``. It |
| 66 |
will be set as :attr:`!__cause__` on the raised exception. Setting |
| 67 |
:attr:`!__cause__` also implicitly sets the :attr:`!__suppress_context__` |
| 68 |
attribute to ``True``, so that using ``raise new_exc from None`` |
| 69 |
effectively replaces the old exception with the new one for display |
| 70 |
purposes (e.g. converting :exc:`KeyError` to :exc:`AttributeError`), while |
| 71 |
leaving the old exception available in :attr:`!__context__` for introspection |
| 72 |
when debugging. |
| 73 |
|
| 74 |
The default traceback display code shows these chained exceptions in |
| 75 |
addition to the traceback for the exception itself. An explicitly chained |
| 76 |
exception in :attr:`!__cause__` is always shown when present. An implicitly |
| 77 |
chained exception in :attr:`!__context__` is shown only if :attr:`!__cause__` |
| 78 |
is :const:`None` and :attr:`!__suppress_context__` is false. |
| 79 |
|
| 80 |
In either case, the exception itself is always shown after any chained |
| 81 |
exceptions so that the final line of the traceback always shows the last |
| 82 |
exception that was raised. |
| 83 |
|
| 84 |
|
| 85 |
Inheriting from built-in exceptions |
| 86 |
----------------------------------- |
| 87 |
|
| 88 |
User code can create subclasses that inherit from an exception type. |
| 89 |
It's recommended to only subclass one exception type at a time to avoid |
| 90 |
any possible conflicts between how the bases handle the ``args`` |
| 91 |
attribute, as well as due to possible memory layout incompatibilities. |
| 92 |
|
| 93 |
.. impl-detail:: |
| 94 |
|
| 95 |
Most built-in exceptions are implemented in C for efficiency, see: |
| 96 |
:source:`Objects/exceptions.c`. Some have custom memory layouts |
| 97 |
which makes it impossible to create a subclass that inherits from |
| 98 |
multiple exception types. The memory layout of a type is an implementation |
| 99 |
detail and might change between Python versions, leading to new |
| 100 |
conflicts in the future. Therefore, it's recommended to avoid |
| 101 |
subclassing multiple exception types altogether. |
| 102 |
|
| 103 |
|
| 104 |
Base classes |
| 105 |
------------ |
| 106 |
|
| 107 |
The following exceptions are used mostly as base classes for other exceptions. |
| 108 |
|
| 109 |
.. exception:: BaseException |
| 110 |
|
| 111 |
The base class for all built-in exceptions. It is not meant to be directly |
| 112 |
inherited by user-defined classes (for that, use :exc:`Exception`). If |
| 113 |
:func:`str` is called on an instance of this class, the representation of |
| 114 |
the argument(s) to the instance are returned, or the empty string when |
| 115 |
there were no arguments. |
| 116 |
|
| 117 |
.. attribute:: args |
| 118 |
|
| 119 |
The tuple of arguments given to the exception constructor. Some built-in |
| 120 |
exceptions (like :exc:`OSError`) expect a certain number of arguments and |
| 121 |
assign a special meaning to the elements of this tuple, while others are |
| 122 |
usually called only with a single string giving an error message. |
| 123 |
|
| 124 |
.. method:: with_traceback(tb) |
| 125 |
|
| 126 |
This method sets *tb* as the new traceback for the exception and returns |
| 127 |
the exception object. It was more commonly used before the exception |
| 128 |
chaining features of :pep:`3134` became available. The following example |
| 129 |
shows how we can convert an instance of ``SomeException`` into an |
| 130 |
instance of ``OtherException`` while preserving the traceback. Once |
| 131 |
raised, the current frame is pushed onto the traceback of the |
| 132 |
``OtherException``, as would have happened to the traceback of the |
| 133 |
original ``SomeException`` had we allowed it to propagate to the caller. :: |
| 134 |
|
| 135 |
try: |
| 136 |
... |
| 137 |
except SomeException: |
| 138 |
tb = sys.exception().__traceback__ |
| 139 |
raise OtherException(...).with_traceback(tb) |
| 140 |
|
| 141 |
.. attribute:: __traceback__ |
| 142 |
|
| 143 |
A writable field that holds the |
| 144 |
:ref:`traceback object <traceback-objects>` associated with this |
| 145 |
exception. See also: :ref:`raise`. |
| 146 |
|
| 147 |
.. method:: add_note(note) |
| 148 |
|
| 149 |
Add the string ``note`` to the exception's notes which appear in the standard |
| 150 |
traceback after the exception string. A :exc:`TypeError` is raised if ``note`` |
| 151 |
is not a string. |
| 152 |
|
| 153 |
.. versionadded:: 3.11 |
| 154 |
|
| 155 |
.. attribute:: __notes__ |
| 156 |
|
| 157 |
A list of the notes of this exception, which were added with :meth:`add_note`. |
| 158 |
This attribute is created when :meth:`add_note` is called. |
| 159 |
|
| 160 |
.. versionadded:: 3.11 |
| 161 |
|
| 162 |
|
| 163 |
.. exception:: Exception |
| 164 |
|
| 165 |
All built-in, non-system-exiting exceptions are derived from this class. All |
| 166 |
user-defined exceptions should also be derived from this class. |
| 167 |
|
| 168 |
|
| 169 |
.. exception:: ArithmeticError |
| 170 |
|
| 171 |
The base class for those built-in exceptions that are raised for various |
| 172 |
arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`, |
| 173 |
:exc:`FloatingPointError`. |
| 174 |
|
| 175 |
|
| 176 |
.. exception:: BufferError |
| 177 |
|
| 178 |
Raised when a :ref:`buffer <bufferobjects>` related operation cannot be |
| 179 |
performed. |
| 180 |
|
| 181 |
|
| 182 |
.. exception:: LookupError |
| 183 |
|
| 184 |
The base class for the exceptions that are raised when a key or index used on |
| 185 |
a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This |
| 186 |
can be raised directly by :func:`codecs.lookup`. |
| 187 |
|
| 188 |
|
| 189 |
Concrete exceptions |
| 190 |
------------------- |
| 191 |
|
| 192 |
The following exceptions are the exceptions that are usually raised. |
| 193 |
|
| 194 |
.. exception:: AssertionError |
| 195 |
|
| 196 |
.. index:: pair: statement; assert |
| 197 |
|
| 198 |
Raised when an :keyword:`assert` statement fails. |
| 199 |
|
| 200 |
|
| 201 |
.. exception:: AttributeError |
| 202 |
|
| 203 |
Raised when an attribute reference (see :ref:`attribute-references`) or |
| 204 |
assignment fails. (When an object does not support attribute references or |
| 205 |
attribute assignments at all, :exc:`TypeError` is raised.) |
| 206 |
|
| 207 |
The optional *name* and *obj* keyword-only arguments |
| 208 |
set the corresponding attributes: |
| 209 |
|
| 210 |
.. attribute:: name |
| 211 |
|
| 212 |
The name of the attribute that was attempted to be accessed. |
| 213 |
|
| 214 |
.. attribute:: obj |
| 215 |
|
| 216 |
The object that was accessed for the named attribute. |
| 217 |
|
| 218 |
.. versionchanged:: 3.10 |
| 219 |
Added the :attr:`name` and :attr:`obj` attributes. |
| 220 |
|
| 221 |
.. exception:: EOFError |
| 222 |
|
| 223 |
Raised when the :func:`input` function hits an end-of-file condition (EOF) |
| 224 |
without reading any data. (Note: the :meth:`io.TextIOBase.read` and |
| 225 |
:meth:`io.IOBase.readline` methods return an empty string when they hit EOF.) |
| 226 |
|
| 227 |
|
| 228 |
.. exception:: FloatingPointError |
| 229 |
|
| 230 |
Not currently used. |
| 231 |
|
| 232 |
|
| 233 |
.. exception:: GeneratorExit |
| 234 |
|
| 235 |
Raised when a :term:`generator` or :term:`coroutine` is closed; |
| 236 |
see :meth:`generator.close` and :meth:`coroutine.close`. It |
| 237 |
directly inherits from :exc:`BaseException` instead of :exc:`Exception` since |
| 238 |
it is technically not an error. |
| 239 |
|
| 240 |
|
| 241 |
.. exception:: ImportError |
| 242 |
|
| 243 |
Raised when the :keyword:`import` statement has troubles trying to |
| 244 |
load a module. Also raised when the "from list" in ``from ... import`` |
| 245 |
has a name that cannot be found. |
| 246 |
|
| 247 |
The optional *name* and *path* keyword-only arguments |
| 248 |
set the corresponding attributes: |
| 249 |
|
| 250 |
.. attribute:: name |
| 251 |
|
| 252 |
The name of the module that was attempted to be imported. |
| 253 |
|
| 254 |
.. attribute:: path |
| 255 |
|
| 256 |
The path to any file which triggered the exception. |
| 257 |
|
| 258 |
.. versionchanged:: 3.3 |
| 259 |
Added the :attr:`name` and :attr:`path` attributes. |
| 260 |
|
| 261 |
.. exception:: ModuleNotFoundError |
| 262 |
|
| 263 |
A subclass of :exc:`ImportError` which is raised by :keyword:`import` |
| 264 |
when a module could not be located. It is also raised when ``None`` |
| 265 |
is found in :data:`sys.modules`. |
| 266 |
|
| 267 |
.. versionadded:: 3.6 |
| 268 |
|
| 269 |
|
| 270 |
.. exception:: IndexError |
| 271 |
|
| 272 |
Raised when a sequence subscript is out of range. (Slice indices are |
| 273 |
silently truncated to fall in the allowed range; if an index is not an |
| 274 |
integer, :exc:`TypeError` is raised.) |
| 275 |
|
| 276 |
.. XXX xref to sequences |
| 277 |
|
| 278 |
|
| 279 |
.. exception:: KeyError |
| 280 |
|
| 281 |
Raised when a mapping (dictionary) key is not found in the set of existing keys. |
| 282 |
|
| 283 |
.. XXX xref to mapping objects? |
| 284 |
|
| 285 |
|
| 286 |
.. exception:: KeyboardInterrupt |
| 287 |
|
| 288 |
Raised when the user hits the interrupt key (normally :kbd:`Control-C` or |
| 289 |
:kbd:`Delete`). During execution, a check for interrupts is made |
| 290 |
regularly. The exception inherits from :exc:`BaseException` so as to not be |
| 291 |
accidentally caught by code that catches :exc:`Exception` and thus prevent |
| 292 |
the interpreter from exiting. |
| 293 |
|
| 294 |
.. note:: |
| 295 |
|
| 296 |
Catching a :exc:`KeyboardInterrupt` requires special consideration. |
| 297 |
Because it can be raised at unpredictable points, it may, in some |
| 298 |
circumstances, leave the running program in an inconsistent state. It is |
| 299 |
generally best to allow :exc:`KeyboardInterrupt` to end the program as |
| 300 |
quickly as possible or avoid raising it entirely. (See |
| 301 |
:ref:`handlers-and-exceptions`.) |
| 302 |
|
| 303 |
|
| 304 |
.. exception:: MemoryError |
| 305 |
|
| 306 |
Raised when an operation runs out of memory but the situation may still be |
| 307 |
rescued (by deleting some objects). The associated value is a string indicating |
| 308 |
what kind of (internal) operation ran out of memory. Note that because of the |
| 309 |
underlying memory management architecture (C's :c:func:`malloc` function), the |
| 310 |
interpreter may not always be able to completely recover from this situation; it |
| 311 |
nevertheless raises an exception so that a stack traceback can be printed, in |
| 312 |
case a run-away program was the cause. |
| 313 |
|
| 314 |
|
| 315 |
.. exception:: NameError |
| 316 |
|
| 317 |
Raised when a local or global name is not found. This applies only to |
| 318 |
unqualified names. The associated value is an error message that includes the |
| 319 |
name that could not be found. |
| 320 |
|
| 321 |
The optional *name* keyword-only argument sets the attribute: |
| 322 |
|
| 323 |
.. attribute:: name |
| 324 |
|
| 325 |
The name of the variable that was attempted to be accessed. |
| 326 |
|
| 327 |
.. versionchanged:: 3.10 |
| 328 |
Added the :attr:`name` attribute. |
| 329 |
|
| 330 |
|
| 331 |
.. exception:: NotImplementedError |
| 332 |
|
| 333 |
This exception is derived from :exc:`RuntimeError`. In user defined base |
| 334 |
classes, abstract methods should raise this exception when they require |
| 335 |
derived classes to override the method, or while the class is being |
| 336 |
developed to indicate that the real implementation still needs to be added. |
| 337 |
|
| 338 |
.. note:: |
| 339 |
|
| 340 |
It should not be used to indicate that an operator or method is not |
| 341 |
meant to be supported at all -- in that case either leave the operator / |
| 342 |
method undefined or, if a subclass, set it to :data:`None`. |
| 343 |
|
| 344 |
.. caution:: |
| 345 |
|
| 346 |
:exc:`!NotImplementedError` and :data:`!NotImplemented` are not |
| 347 |
interchangeable. This exception should only be used as described |
| 348 |
above; see :data:`NotImplemented` for details on correct usage of |
| 349 |
the built-in constant. |
| 350 |
|
| 351 |
|
| 352 |
.. exception:: OSError([arg]) |
| 353 |
OSError(errno, strerror[, filename[, winerror[, filename2]]]) |
| 354 |
|
| 355 |
.. index:: pair: module; errno |
| 356 |
|
| 357 |
This exception is raised when a system function returns a system-related |
| 358 |
error, including I/O failures such as "file not found" or "disk full" |
| 359 |
(not for illegal argument types or other incidental errors). |
| 360 |
|
| 361 |
The second form of the constructor sets the corresponding attributes, |
| 362 |
described below. The attributes default to :const:`None` if not |
| 363 |
specified. For backwards compatibility, if three arguments are passed, |
| 364 |
the :attr:`~BaseException.args` attribute contains only a 2-tuple |
| 365 |
of the first two constructor arguments. |
| 366 |
|
| 367 |
The constructor often actually returns a subclass of :exc:`OSError`, as |
| 368 |
described in `OS exceptions`_ below. The particular subclass depends on |
| 369 |
the final :attr:`.errno` value. This behaviour only occurs when |
| 370 |
constructing :exc:`OSError` directly or via an alias, and is not |
| 371 |
inherited when subclassing. |
| 372 |
|
| 373 |
.. attribute:: errno |
| 374 |
|
| 375 |
A numeric error code from the C variable :c:data:`errno`. |
| 376 |
|
| 377 |
.. attribute:: winerror |
| 378 |
|
| 379 |
Under Windows, this gives you the native |
| 380 |
Windows error code. The :attr:`.errno` attribute is then an approximate |
| 381 |
translation, in POSIX terms, of that native error code. |
| 382 |
|
| 383 |
Under Windows, if the *winerror* constructor argument is an integer, |
| 384 |
the :attr:`.errno` attribute is determined from the Windows error code, |
| 385 |
and the *errno* argument is ignored. On other platforms, the |
| 386 |
*winerror* argument is ignored, and the :attr:`winerror` attribute |
| 387 |
does not exist. |
| 388 |
|
| 389 |
.. attribute:: strerror |
| 390 |
|
| 391 |
The corresponding error message, as provided by |
| 392 |
the operating system. It is formatted by the C |
| 393 |
functions :c:func:`!perror` under POSIX, and :c:func:`!FormatMessage` |
| 394 |
under Windows. |
| 395 |
|
| 396 |
.. attribute:: filename |
| 397 |
filename2 |
| 398 |
|
| 399 |
For exceptions that involve a file system path (such as :func:`open` or |
| 400 |
:func:`os.unlink`), :attr:`filename` is the file name passed to the function. |
| 401 |
For functions that involve two file system paths (such as |
| 402 |
:func:`os.rename`), :attr:`filename2` corresponds to the second |
| 403 |
file name passed to the function. |
| 404 |
|
| 405 |
|
| 406 |
.. versionchanged:: 3.3 |
| 407 |
:exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`, |
| 408 |
:exc:`socket.error`, :exc:`select.error` and |
| 409 |
:exc:`!mmap.error` have been merged into :exc:`OSError`, and the |
| 410 |
constructor may return a subclass. |
| 411 |
|
| 412 |
.. versionchanged:: 3.4 |
| 413 |
The :attr:`filename` attribute is now the original file name passed to |
| 414 |
the function, instead of the name encoded to or decoded from the |
| 415 |
:term:`filesystem encoding and error handler`. Also, the *filename2* |
| 416 |
constructor argument and attribute was added. |
| 417 |
|
| 418 |
|
| 419 |
.. exception:: OverflowError |
| 420 |
|
| 421 |
Raised when the result of an arithmetic operation is too large to be |
| 422 |
represented. This cannot occur for integers (which would rather raise |
| 423 |
:exc:`MemoryError` than give up). However, for historical reasons, |
| 424 |
OverflowError is sometimes raised for integers that are outside a required |
| 425 |
range. Because of the lack of standardization of floating-point exception |
| 426 |
handling in C, most floating-point operations are not checked. |
| 427 |
|
| 428 |
|
| 429 |
.. exception:: PythonFinalizationError |
| 430 |
|
| 431 |
This exception is derived from :exc:`RuntimeError`. It is raised when |
| 432 |
an operation is blocked during interpreter shutdown also known as |
| 433 |
:term:`Python finalization <interpreter shutdown>`. |
| 434 |
|
| 435 |
Examples of operations which can be blocked with a |
| 436 |
:exc:`PythonFinalizationError` during the Python finalization: |
| 437 |
|
| 438 |
* Creating a new Python thread. |
| 439 |
* :meth:`Joining <threading.Thread.join>` a running daemon thread. |
| 440 |
* :func:`os.fork`. |
| 441 |
|
| 442 |
See also the :func:`sys.is_finalizing` function. |
| 443 |
|
| 444 |
.. versionadded:: 3.13 |
| 445 |
Previously, a plain :exc:`RuntimeError` was raised. |
| 446 |
|
| 447 |
.. versionchanged:: 3.14 |
| 448 |
|
| 449 |
:meth:`threading.Thread.join` can now raise this exception. |
| 450 |
|
| 451 |
.. exception:: RecursionError |
| 452 |
|
| 453 |
This exception is derived from :exc:`RuntimeError`. It is raised when the |
| 454 |
interpreter detects that the maximum recursion depth (see |
| 455 |
:func:`sys.getrecursionlimit`) is exceeded. |
| 456 |
|
| 457 |
.. versionadded:: 3.5 |
| 458 |
Previously, a plain :exc:`RuntimeError` was raised. |
| 459 |
|
| 460 |
|
| 461 |
.. exception:: ReferenceError |
| 462 |
|
| 463 |
This exception is raised when a weak reference proxy, created by the |
| 464 |
:func:`weakref.proxy` function, is used to access an attribute of the referent |
| 465 |
after it has been garbage collected. For more information on weak references, |
| 466 |
see the :mod:`weakref` module. |
| 467 |
|
| 468 |
|
| 469 |
.. exception:: RuntimeError |
| 470 |
|
| 471 |
Raised when an error is detected that doesn't fall in any of the other |
| 472 |
categories. The associated value is a string indicating what precisely went |
| 473 |
wrong. |
| 474 |
|
| 475 |
|
| 476 |
.. exception:: StopIteration |
| 477 |
|
| 478 |
Raised by built-in function :func:`next` and an :term:`iterator`\'s |
| 479 |
:meth:`~iterator.__next__` method to signal that there are no further |
| 480 |
items produced by the iterator. |
| 481 |
|
| 482 |
.. attribute:: StopIteration.value |
| 483 |
|
| 484 |
The exception object has a single attribute :attr:`!value`, which is |
| 485 |
given as an argument when constructing the exception, and defaults |
| 486 |
to :const:`None`. |
| 487 |
|
| 488 |
When a :term:`generator` or :term:`coroutine` function |
| 489 |
returns, a new :exc:`StopIteration` instance is |
| 490 |
raised, and the value returned by the function is used as the |
| 491 |
:attr:`value` parameter to the constructor of the exception. |
| 492 |
|
| 493 |
If a generator code directly or indirectly raises :exc:`StopIteration`, |
| 494 |
it is converted into a :exc:`RuntimeError` (retaining the |
| 495 |
:exc:`StopIteration` as the new exception's cause). |
| 496 |
|
| 497 |
.. versionchanged:: 3.3 |
| 498 |
Added ``value`` attribute and the ability for generator functions to |
| 499 |
use it to return a value. |
| 500 |
|
| 501 |
.. versionchanged:: 3.5 |
| 502 |
Introduced the RuntimeError transformation via |
| 503 |
``from __future__ import generator_stop``, see :pep:`479`. |
| 504 |
|
| 505 |
.. versionchanged:: 3.7 |
| 506 |
Enable :pep:`479` for all code by default: a :exc:`StopIteration` |
| 507 |
error raised in a generator is transformed into a :exc:`RuntimeError`. |
| 508 |
|
| 509 |
.. exception:: StopAsyncIteration |
| 510 |
|
| 511 |
Must be raised by :meth:`~object.__anext__` method of an |
| 512 |
:term:`asynchronous iterator` object to stop the iteration. |
| 513 |
|
| 514 |
.. versionadded:: 3.5 |
| 515 |
|
| 516 |
.. exception:: SyntaxError(message, details) |
| 517 |
|
| 518 |
Raised when the parser encounters a syntax error. This may occur in an |
| 519 |
:keyword:`import` statement, in a call to the built-in functions |
| 520 |
:func:`compile`, :func:`exec`, |
| 521 |
or :func:`eval`, or when reading the initial script or standard input |
| 522 |
(also interactively). |
| 523 |
|
| 524 |
The :func:`str` of the exception instance returns only the error message. |
| 525 |
Details is a tuple whose members are also available as separate attributes. |
| 526 |
|
| 527 |
.. attribute:: filename |
| 528 |
|
| 529 |
The name of the file the syntax error occurred in. |
| 530 |
|
| 531 |
.. attribute:: lineno |
| 532 |
|
| 533 |
Which line number in the file the error occurred in. This is |
| 534 |
1-indexed: the first line in the file has a ``lineno`` of 1. |
| 535 |
|
| 536 |
.. attribute:: offset |
| 537 |
|
| 538 |
The column in the line where the error occurred. This is |
| 539 |
1-indexed: the first character in the line has an ``offset`` of 1. |
| 540 |
|
| 541 |
.. attribute:: text |
| 542 |
|
| 543 |
The source code text involved in the error. |
| 544 |
|
| 545 |
.. attribute:: end_lineno |
| 546 |
|
| 547 |
Which line number in the file the error occurred ends in. This is |
| 548 |
1-indexed: the first line in the file has a ``lineno`` of 1. |
| 549 |
|
| 550 |
.. attribute:: end_offset |
| 551 |
|
| 552 |
The column in the end line where the error occurred finishes. This is |
| 553 |
1-indexed: the first character in the line has an ``offset`` of 1. |
| 554 |
|
| 555 |
For errors in f-string fields, the message is prefixed by "f-string: " |
| 556 |
and the offsets are offsets in a text constructed from the replacement |
| 557 |
expression. For example, compiling f'Bad {a b} field' results in this |
| 558 |
args attribute: ('f-string: ...', ('', 1, 2, '(a b)\n', 1, 5)). |
| 559 |
|
| 560 |
.. versionchanged:: 3.10 |
| 561 |
Added the :attr:`end_lineno` and :attr:`end_offset` attributes. |
| 562 |
|
| 563 |
.. exception:: IndentationError |
| 564 |
|
| 565 |
Base class for syntax errors related to incorrect indentation. This is a |
| 566 |
subclass of :exc:`SyntaxError`. |
| 567 |
|
| 568 |
|
| 569 |
.. exception:: TabError |
| 570 |
|
| 571 |
Raised when indentation contains an inconsistent use of tabs and spaces. |
| 572 |
This is a subclass of :exc:`IndentationError`. |
| 573 |
|
| 574 |
|
| 575 |
.. exception:: SystemError |
| 576 |
|
| 577 |
Raised when the interpreter finds an internal error, but the situation does not |
| 578 |
look so serious to cause it to abandon all hope. The associated value is a |
| 579 |
string indicating what went wrong (in low-level terms). In :term:`CPython`, |
| 580 |
this could be raised by incorrectly using Python's C API, such as returning |
| 581 |
a ``NULL`` value without an exception set. |
| 582 |
|
| 583 |
If you're confident that this exception wasn't your fault, or the fault of |
| 584 |
a package you're using, you should report this to the author or maintainer |
| 585 |
of your Python interpreter. |
| 586 |
Be sure to report the version of the Python interpreter (``sys.version``; it is |
| 587 |
also printed at the start of an interactive Python session), the exact error |
| 588 |
message (the exception's associated value) and if possible the source of the |
| 589 |
program that triggered the error. |
| 590 |
|
| 591 |
|
| 592 |
.. exception:: SystemExit |
| 593 |
|
| 594 |
This exception is raised by the :func:`sys.exit` function. It inherits from |
| 595 |
:exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally |
| 596 |
caught by code that catches :exc:`Exception`. This allows the exception to |
| 597 |
properly propagate up and cause the interpreter to exit. When it is not |
| 598 |
handled, the Python interpreter exits; no stack traceback is printed. The |
| 599 |
constructor accepts the same optional argument passed to :func:`sys.exit`. |
| 600 |
If the value is an integer, it specifies the system exit status (passed to |
| 601 |
C's :c:func:`!exit` function); if it is ``None``, the exit status is zero; if |
| 602 |
it has another type (such as a string), the object's value is printed and |
| 603 |
the exit status is one. |
| 604 |
|
| 605 |
A call to :func:`sys.exit` is translated into an exception so that clean-up |
| 606 |
handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be |
| 607 |
executed, and so that a debugger can execute a script without running the risk |
| 608 |
of losing control. The :func:`os._exit` function can be used if it is |
| 609 |
absolutely positively necessary to exit immediately (for example, in the child |
| 610 |
process after a call to :func:`os.fork`). |
| 611 |
|
| 612 |
.. attribute:: code |
| 613 |
|
| 614 |
The exit status or error message that is passed to the constructor. |
| 615 |
(Defaults to ``None``.) |
| 616 |
|
| 617 |
|
| 618 |
.. exception:: TypeError |
| 619 |
|
| 620 |
Raised when an operation or function is applied to an object of inappropriate |
| 621 |
type. The associated value is a string giving details about the type mismatch. |
| 622 |
|
| 623 |
This exception may be raised by user code to indicate that an attempted |
| 624 |
operation on an object is not supported, and is not meant to be. If an object |
| 625 |
is meant to support a given operation but has not yet provided an |
| 626 |
implementation, :exc:`NotImplementedError` is the proper exception to raise. |
| 627 |
|
| 628 |
Passing arguments of the wrong type (e.g. passing a :class:`list` when an |
| 629 |
:class:`int` is expected) should result in a :exc:`TypeError`, but passing |
| 630 |
arguments with the wrong value (e.g. a number outside expected boundaries) |
| 631 |
should result in a :exc:`ValueError`. |
| 632 |
|
| 633 |
.. exception:: UnboundLocalError |
| 634 |
|
| 635 |
Raised when a reference is made to a local variable in a function or method, but |
| 636 |
no value has been bound to that variable. This is a subclass of |
| 637 |
:exc:`NameError`. |
| 638 |
|
| 639 |
|
| 640 |
.. exception:: UnicodeError |
| 641 |
|
| 642 |
Raised when a Unicode-related encoding or decoding error occurs. It is a |
| 643 |
subclass of :exc:`ValueError`. |
| 644 |
|
| 645 |
:exc:`UnicodeError` has attributes that describe the encoding or decoding |
| 646 |
error. For example, ``err.object[err.start:err.end]`` gives the particular |
| 647 |
invalid input that the codec failed on. |
| 648 |
|
| 649 |
.. attribute:: encoding |
| 650 |
|
| 651 |
The name of the encoding that raised the error. |
| 652 |
|
| 653 |
.. attribute:: reason |
| 654 |
|
| 655 |
A string describing the specific codec error. |
| 656 |
|
| 657 |
.. attribute:: object |
| 658 |
|
| 659 |
The object the codec was attempting to encode or decode. |
| 660 |
|
| 661 |
.. attribute:: start |
| 662 |
|
| 663 |
The first index of invalid data in :attr:`object`. |
| 664 |
|
| 665 |
This value should not be negative as it is interpreted as an |
| 666 |
absolute offset but this constraint is not enforced at runtime. |
| 667 |
|
| 668 |
.. attribute:: end |
| 669 |
|
| 670 |
The index after the last invalid data in :attr:`object`. |
| 671 |
|
| 672 |
This value should not be negative as it is interpreted as an |
| 673 |
absolute offset but this constraint is not enforced at runtime. |
| 674 |
|
| 675 |
|
| 676 |
.. exception:: UnicodeEncodeError |
| 677 |
|
| 678 |
Raised when a Unicode-related error occurs during encoding. It is a subclass of |
| 679 |
:exc:`UnicodeError`. |
| 680 |
|
| 681 |
|
| 682 |
.. exception:: UnicodeDecodeError |
| 683 |
|
| 684 |
Raised when a Unicode-related error occurs during decoding. It is a subclass of |
| 685 |
:exc:`UnicodeError`. |
| 686 |
|
| 687 |
|
| 688 |
.. exception:: UnicodeTranslateError |
| 689 |
|
| 690 |
Raised when a Unicode-related error occurs during translating. It is a subclass |
| 691 |
of :exc:`UnicodeError`. |
| 692 |
|
| 693 |
|
| 694 |
.. exception:: ValueError |
| 695 |
|
| 696 |
Raised when an operation or function receives an argument that has the |
| 697 |
right type but an inappropriate value, and the situation is not described by a |
| 698 |
more precise exception such as :exc:`IndexError`. |
| 699 |
|
| 700 |
|
| 701 |
.. exception:: ZeroDivisionError |
| 702 |
|
| 703 |
Raised when the second argument of a division or modulo operation is zero. The |
| 704 |
associated value is a string indicating the type of the operands and the |
| 705 |
operation. |
| 706 |
|
| 707 |
|
| 708 |
The following exceptions are kept for compatibility with previous versions; |
| 709 |
starting from Python 3.3, they are aliases of :exc:`OSError`. |
| 710 |
|
| 711 |
.. exception:: EnvironmentError |
| 712 |
|
| 713 |
.. exception:: IOError |
| 714 |
|
| 715 |
.. exception:: WindowsError |
| 716 |
|
| 717 |
Only available on Windows. |
| 718 |
|
| 719 |
|
| 720 |
OS exceptions |
| 721 |
^^^^^^^^^^^^^ |
| 722 |
|
| 723 |
The following exceptions are subclasses of :exc:`OSError`, they get raised |
| 724 |
depending on the system error code. |
| 725 |
|
| 726 |
.. exception:: BlockingIOError |
| 727 |
|
| 728 |
Raised when an operation would block on an object (e.g. socket) set |
| 729 |
for non-blocking operation. |
| 730 |
Corresponds to :c:data:`errno` :py:const:`~errno.EAGAIN`, :py:const:`~errno.EALREADY`, |
| 731 |
:py:const:`~errno.EWOULDBLOCK` and :py:const:`~errno.EINPROGRESS`. |
| 732 |
|
| 733 |
In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have |
| 734 |
one more attribute: |
| 735 |
|
| 736 |
.. attribute:: characters_written |
| 737 |
|
| 738 |
An integer containing the number of **bytes** written to the stream |
| 739 |
before it blocked. This attribute is available when using the |
| 740 |
buffered I/O classes from the :mod:`io` module. |
| 741 |
|
| 742 |
.. exception:: ChildProcessError |
| 743 |
|
| 744 |
Raised when an operation on a child process failed. |
| 745 |
Corresponds to :c:data:`errno` :py:const:`~errno.ECHILD`. |
| 746 |
|
| 747 |
.. exception:: ConnectionError |
| 748 |
|
| 749 |
A base class for connection-related issues. |
| 750 |
|
| 751 |
Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`, |
| 752 |
:exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`. |
| 753 |
|
| 754 |
.. exception:: BrokenPipeError |
| 755 |
|
| 756 |
A subclass of :exc:`ConnectionError`, raised when trying to write on a |
| 757 |
pipe while the other end has been closed, or trying to write on a socket |
| 758 |
which has been shutdown for writing. |
| 759 |
Corresponds to :c:data:`errno` :py:const:`~errno.EPIPE` and :py:const:`~errno.ESHUTDOWN`. |
| 760 |
|
| 761 |
.. exception:: ConnectionAbortedError |
| 762 |
|
| 763 |
A subclass of :exc:`ConnectionError`, raised when a connection attempt |
| 764 |
is aborted by the peer. |
| 765 |
Corresponds to :c:data:`errno` :py:const:`~errno.ECONNABORTED`. |
| 766 |
|
| 767 |
.. exception:: ConnectionRefusedError |
| 768 |
|
| 769 |
A subclass of :exc:`ConnectionError`, raised when a connection attempt |
| 770 |
is refused by the peer. |
| 771 |
Corresponds to :c:data:`errno` :py:const:`~errno.ECONNREFUSED`. |
| 772 |
|
| 773 |
.. exception:: ConnectionResetError |
| 774 |
|
| 775 |
A subclass of :exc:`ConnectionError`, raised when a connection is |
| 776 |
reset by the peer. |
| 777 |
Corresponds to :c:data:`errno` :py:const:`~errno.ECONNRESET`. |
| 778 |
|
| 779 |
.. exception:: FileExistsError |
| 780 |
|
| 781 |
Raised when trying to create a file or directory which already exists. |
| 782 |
Corresponds to :c:data:`errno` :py:const:`~errno.EEXIST`. |
| 783 |
|
| 784 |
.. exception:: FileNotFoundError |
| 785 |
|
| 786 |
Raised when a file or directory is requested but doesn't exist. |
| 787 |
Corresponds to :c:data:`errno` :py:const:`~errno.ENOENT`. |
| 788 |
|
| 789 |
.. exception:: InterruptedError |
| 790 |
|
| 791 |
Raised when a system call is interrupted by an incoming signal. |
| 792 |
Corresponds to :c:data:`errno` :py:const:`~errno.EINTR`. |
| 793 |
|
| 794 |
.. versionchanged:: 3.5 |
| 795 |
Python now retries system calls when a syscall is interrupted by a |
| 796 |
signal, except if the signal handler raises an exception (see :pep:`475` |
| 797 |
for the rationale), instead of raising :exc:`InterruptedError`. |
| 798 |
|
| 799 |
.. exception:: IsADirectoryError |
| 800 |
|
| 801 |
Raised when a file operation (such as :func:`os.remove`) is requested |
| 802 |
on a directory. |
| 803 |
Corresponds to :c:data:`errno` :py:const:`~errno.EISDIR`. |
| 804 |
|
| 805 |
.. exception:: NotADirectoryError |
| 806 |
|
| 807 |
Raised when a directory operation (such as :func:`os.listdir`) is requested on |
| 808 |
something which is not a directory. On most POSIX platforms, it may also be |
| 809 |
raised if an operation attempts to open or traverse a non-directory file as if |
| 810 |
it were a directory. |
| 811 |
Corresponds to :c:data:`errno` :py:const:`~errno.ENOTDIR`. |
| 812 |
|
| 813 |
.. exception:: PermissionError |
| 814 |
|
| 815 |
Raised when trying to run an operation without the adequate access |
| 816 |
rights - for example filesystem permissions. |
| 817 |
Corresponds to :c:data:`errno` :py:const:`~errno.EACCES`, |
| 818 |
:py:const:`~errno.EPERM`, and :py:const:`~errno.ENOTCAPABLE`. |
| 819 |
|
| 820 |
.. versionchanged:: 3.11.1 |
| 821 |
WASI's :py:const:`~errno.ENOTCAPABLE` is now mapped to |
| 822 |
:exc:`PermissionError`. |
| 823 |
|
| 824 |
.. exception:: ProcessLookupError |
| 825 |
|
| 826 |
Raised when a given process doesn't exist. |
| 827 |
Corresponds to :c:data:`errno` :py:const:`~errno.ESRCH`. |
| 828 |
|
| 829 |
.. exception:: TimeoutError |
| 830 |
|
| 831 |
Raised when a system function timed out at the system level. |
| 832 |
Corresponds to :c:data:`errno` :py:const:`~errno.ETIMEDOUT`. |
| 833 |
|
| 834 |
.. versionadded:: 3.3 |
| 835 |
All the above :exc:`OSError` subclasses were added. |
| 836 |
|
| 837 |
|
| 838 |
.. seealso:: |
| 839 |
|
| 840 |
:pep:`3151` - Reworking the OS and IO exception hierarchy |
| 841 |
|
| 842 |
|
| 843 |
.. _warning-categories-as-exceptions: |
| 844 |
|
| 845 |
Warnings |
| 846 |
-------- |
| 847 |
|
| 848 |
The following exceptions are used as warning categories; see the |
| 849 |
:ref:`warning-categories` documentation for more details. |
| 850 |
|
| 851 |
.. exception:: Warning |
| 852 |
|
| 853 |
Base class for warning categories. |
| 854 |
|
| 855 |
|
| 856 |
.. exception:: UserWarning |
| 857 |
|
| 858 |
Base class for warnings generated by user code. |
| 859 |
|
| 860 |
|
| 861 |
.. exception:: DeprecationWarning |
| 862 |
|
| 863 |
Base class for warnings about deprecated features when those warnings are |
| 864 |
intended for other Python developers. |
| 865 |
|
| 866 |
Ignored by the default warning filters, except in the ``__main__`` module |
| 867 |
(:pep:`565`). Enabling the :ref:`Python Development Mode <devmode>` shows |
| 868 |
this warning. |
| 869 |
|
| 870 |
The deprecation policy is described in :pep:`387`. |
| 871 |
|
| 872 |
|
| 873 |
.. exception:: PendingDeprecationWarning |
| 874 |
|
| 875 |
Base class for warnings about features which are obsolete and |
| 876 |
expected to be deprecated in the future, but are not deprecated |
| 877 |
at the moment. |
| 878 |
|
| 879 |
This class is rarely used as emitting a warning about a possible |
| 880 |
upcoming deprecation is unusual, and :exc:`DeprecationWarning` |
| 881 |
is preferred for already active deprecations. |
| 882 |
|
| 883 |
Ignored by the default warning filters. Enabling the :ref:`Python |
| 884 |
Development Mode <devmode>` shows this warning. |
| 885 |
|
| 886 |
The deprecation policy is described in :pep:`387`. |
| 887 |
|
| 888 |
|
| 889 |
.. exception:: SyntaxWarning |
| 890 |
|
| 891 |
Base class for warnings about dubious syntax. |
| 892 |
|
| 893 |
This warning is typically emitted when compiling Python source code, and usually won't be reported |
| 894 |
when running already compiled code. |
| 895 |
|
| 896 |
|
| 897 |
.. exception:: RuntimeWarning |
| 898 |
|
| 899 |
Base class for warnings about dubious runtime behavior. |
| 900 |
|
| 901 |
|
| 902 |
.. exception:: FutureWarning |
| 903 |
|
| 904 |
Base class for warnings about deprecated features when those warnings are |
| 905 |
intended for end users of applications that are written in Python. |
| 906 |
|
| 907 |
|
| 908 |
.. exception:: ImportWarning |
| 909 |
|
| 910 |
Base class for warnings about probable mistakes in module imports. |
| 911 |
|
| 912 |
Ignored by the default warning filters. Enabling the :ref:`Python |
| 913 |
Development Mode <devmode>` shows this warning. |
| 914 |
|
| 915 |
|
| 916 |
.. exception:: UnicodeWarning |
| 917 |
|
| 918 |
Base class for warnings related to Unicode. |
| 919 |
|
| 920 |
|
| 921 |
.. exception:: EncodingWarning |
| 922 |
|
| 923 |
Base class for warnings related to encodings. |
| 924 |
|
| 925 |
See :ref:`io-encoding-warning` for details. |
| 926 |
|
| 927 |
.. versionadded:: 3.10 |
| 928 |
|
| 929 |
|
| 930 |
.. exception:: BytesWarning |
| 931 |
|
| 932 |
Base class for warnings related to :class:`bytes` and :class:`bytearray`. |
| 933 |
|
| 934 |
|
| 935 |
.. exception:: ResourceWarning |
| 936 |
|
| 937 |
Base class for warnings related to resource usage. |
| 938 |
|
| 939 |
Ignored by the default warning filters. Enabling the :ref:`Python |
| 940 |
Development Mode <devmode>` shows this warning. |
| 941 |
|
| 942 |
.. versionadded:: 3.2 |
| 943 |
|
| 944 |
|
| 945 |
.. _lib-exception-groups: |
| 946 |
|
| 947 |
Exception groups |
| 948 |
---------------- |
| 949 |
|
| 950 |
The following are used when it is necessary to raise multiple unrelated |
| 951 |
exceptions. They are part of the exception hierarchy so they can be |
| 952 |
handled with :keyword:`except` like all other exceptions. In addition, |
| 953 |
they are recognised by :keyword:`except*<except_star>`, which matches |
| 954 |
their subgroups based on the types of the contained exceptions. |
| 955 |
|
| 956 |
.. exception:: ExceptionGroup(msg, excs) |
| 957 |
.. exception:: BaseExceptionGroup(msg, excs) |
| 958 |
|
| 959 |
Both of these exception types wrap the exceptions in the sequence ``excs``. |
| 960 |
The ``msg`` parameter must be a string. The difference between the two |
| 961 |
classes is that :exc:`BaseExceptionGroup` extends :exc:`BaseException` and |
| 962 |
it can wrap any exception, while :exc:`ExceptionGroup` extends :exc:`Exception` |
| 963 |
and it can only wrap subclasses of :exc:`Exception`. This design is so that |
| 964 |
``except Exception`` catches an :exc:`ExceptionGroup` but not |
| 965 |
:exc:`BaseExceptionGroup`. |
| 966 |
|
| 967 |
The :exc:`BaseExceptionGroup` constructor returns an :exc:`ExceptionGroup` |
| 968 |
rather than a :exc:`BaseExceptionGroup` if all contained exceptions are |
| 969 |
:exc:`Exception` instances, so it can be used to make the selection |
| 970 |
automatic. The :exc:`ExceptionGroup` constructor, on the other hand, |
| 971 |
raises a :exc:`TypeError` if any contained exception is not an |
| 972 |
:exc:`Exception` subclass. |
| 973 |
|
| 974 |
.. impl-detail:: |
| 975 |
|
| 976 |
The ``excs`` parameter may be any sequence, but lists and tuples are |
| 977 |
specifically processed more efficiently here. For optimal performance, |
| 978 |
pass a tuple as ``excs``. |
| 979 |
|
| 980 |
.. attribute:: message |
| 981 |
|
| 982 |
The ``msg`` argument to the constructor. This is a read-only attribute. |
| 983 |
|
| 984 |
.. attribute:: exceptions |
| 985 |
|
| 986 |
A tuple of the exceptions in the ``excs`` sequence given to the |
| 987 |
constructor. This is a read-only attribute. |
| 988 |
|
| 989 |
.. method:: subgroup(condition) |
| 990 |
|
| 991 |
Returns an exception group that contains only the exceptions from the |
| 992 |
current group that match *condition*, or ``None`` if the result is empty. |
| 993 |
|
| 994 |
The condition can be an exception type or tuple of exception types, in which |
| 995 |
case each exception is checked for a match using the same check that is used |
| 996 |
in an ``except`` clause. The condition can also be a callable (other than |
| 997 |
a type object) that accepts an exception as its single argument and returns |
| 998 |
true for the exceptions that should be in the subgroup. |
| 999 |
|
| 1000 |
The nesting structure of the current exception is preserved in the result, |
| 1001 |
as are the values of its :attr:`message`, |
| 1002 |
:attr:`~BaseException.__traceback__`, :attr:`~BaseException.__cause__`, |
| 1003 |
:attr:`~BaseException.__context__` and |
| 1004 |
:attr:`~BaseException.__notes__` fields. |
| 1005 |
Empty nested groups are omitted from the result. |
| 1006 |
|
| 1007 |
The condition is checked for all exceptions in the nested exception group, |
| 1008 |
including the top-level and any nested exception groups. If the condition is |
| 1009 |
true for such an exception group, it is included in the result in full. |
| 1010 |
|
| 1011 |
.. versionadded:: 3.13 |
| 1012 |
``condition`` can be any callable which is not a type object. |
| 1013 |
|
| 1014 |
.. method:: split(condition) |
| 1015 |
|
| 1016 |
Like :meth:`subgroup`, but returns the pair ``(match, rest)`` where ``match`` |
| 1017 |
is ``subgroup(condition)`` and ``rest`` is the remaining non-matching |
| 1018 |
part. |
| 1019 |
|
| 1020 |
.. method:: derive(excs) |
| 1021 |
|
| 1022 |
Returns an exception group with the same :attr:`message`, but which |
| 1023 |
wraps the exceptions in ``excs``. |
| 1024 |
|
| 1025 |
This method is used by :meth:`subgroup` and :meth:`split`, which |
| 1026 |
are used in various contexts to break up an exception group. A |
| 1027 |
subclass needs to override it in order to make :meth:`subgroup` |
| 1028 |
and :meth:`split` return instances of the subclass rather |
| 1029 |
than :exc:`ExceptionGroup`. |
| 1030 |
|
| 1031 |
:meth:`subgroup` and :meth:`split` copy the |
| 1032 |
:attr:`~BaseException.__traceback__`, |
| 1033 |
:attr:`~BaseException.__cause__`, :attr:`~BaseException.__context__` and |
| 1034 |
:attr:`~BaseException.__notes__` fields from |
| 1035 |
the original exception group to the one returned by :meth:`derive`, so |
| 1036 |
these fields do not need to be updated by :meth:`derive`. |
| 1037 |
|
| 1038 |
.. doctest:: |
| 1039 |
|
| 1040 |
>>> class MyGroup(ExceptionGroup): |
| 1041 |
... def derive(self, excs): |
| 1042 |
... return MyGroup(self.message, excs) |
| 1043 |
... |
| 1044 |
>>> e = MyGroup("eg", [ValueError(1), TypeError(2)]) |
| 1045 |
>>> e.add_note("a note") |
| 1046 |
>>> e.__context__ = Exception("context") |
| 1047 |
>>> e.__cause__ = Exception("cause") |
| 1048 |
>>> try: |
| 1049 |
... raise e |
| 1050 |
... except Exception as e: |
| 1051 |
... exc = e |
| 1052 |
... |
| 1053 |
>>> match, rest = exc.split(ValueError) |
| 1054 |
>>> exc, exc.__context__, exc.__cause__, exc.__notes__ |
| 1055 |
(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), ['a note']) |
| 1056 |
>>> match, match.__context__, match.__cause__, match.__notes__ |
| 1057 |
(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note']) |
| 1058 |
>>> rest, rest.__context__, rest.__cause__, rest.__notes__ |
| 1059 |
(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note']) |
| 1060 |
>>> exc.__traceback__ is match.__traceback__ is rest.__traceback__ |
| 1061 |
True |
| 1062 |
|
| 1063 |
|
| 1064 |
Note that :exc:`BaseExceptionGroup` defines :meth:`~object.__new__`, so |
| 1065 |
subclasses that need a different constructor signature need to |
| 1066 |
override that rather than :meth:`~object.__init__`. For example, the following |
| 1067 |
defines an exception group subclass which accepts an exit_code and |
| 1068 |
constructs the group's message from it. :: |
| 1069 |
|
| 1070 |
class Errors(ExceptionGroup): |
| 1071 |
def __new__(cls, errors, exit_code): |
| 1072 |
self = super().__new__(Errors, f"exit code: {exit_code}", errors) |
| 1073 |
self.exit_code = exit_code |
| 1074 |
return self |
| 1075 |
|
| 1076 |
def derive(self, excs): |
| 1077 |
return Errors(excs, self.exit_code) |
| 1078 |
|
| 1079 |
Like :exc:`ExceptionGroup`, any subclass of :exc:`BaseExceptionGroup` which |
| 1080 |
is also a subclass of :exc:`Exception` can only wrap instances of |
| 1081 |
:exc:`Exception`. |
| 1082 |
|
| 1083 |
.. versionadded:: 3.11 |
| 1084 |
|
| 1085 |
|
| 1086 |
Exception hierarchy |
| 1087 |
------------------- |
| 1088 |
|
| 1089 |
The class hierarchy for built-in exceptions is: |
| 1090 |
|
| 1091 |
.. literalinclude:: ../../Lib/test/exception_hierarchy.txt |
| 1092 |
:language: text |