Debian Codegraph @

Doc/library/exceptions.rst

raw
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 * :func:`os.fork`.
440
441 See also the :func:`sys.is_finalizing` function.
442
443 .. versionadded:: 3.13
444 Previously, a plain :exc:`RuntimeError` was raised.
445
446
447 .. exception:: RecursionError
448
449 This exception is derived from :exc:`RuntimeError`. It is raised when the
450 interpreter detects that the maximum recursion depth (see
451 :func:`sys.getrecursionlimit`) is exceeded.
452
453 .. versionadded:: 3.5
454 Previously, a plain :exc:`RuntimeError` was raised.
455
456
457 .. exception:: ReferenceError
458
459 This exception is raised when a weak reference proxy, created by the
460 :func:`weakref.proxy` function, is used to access an attribute of the referent
461 after it has been garbage collected. For more information on weak references,
462 see the :mod:`weakref` module.
463
464
465 .. exception:: RuntimeError
466
467 Raised when an error is detected that doesn't fall in any of the other
468 categories. The associated value is a string indicating what precisely went
469 wrong.
470
471
472 .. exception:: StopIteration
473
474 Raised by built-in function :func:`next` and an :term:`iterator`\'s
475 :meth:`~iterator.__next__` method to signal that there are no further
476 items produced by the iterator.
477
478 .. attribute:: StopIteration.value
479
480 The exception object has a single attribute :attr:`!value`, which is
481 given as an argument when constructing the exception, and defaults
482 to :const:`None`.
483
484 When a :term:`generator` or :term:`coroutine` function
485 returns, a new :exc:`StopIteration` instance is
486 raised, and the value returned by the function is used as the
487 :attr:`value` parameter to the constructor of the exception.
488
489 If a generator code directly or indirectly raises :exc:`StopIteration`,
490 it is converted into a :exc:`RuntimeError` (retaining the
491 :exc:`StopIteration` as the new exception's cause).
492
493 .. versionchanged:: 3.3
494 Added ``value`` attribute and the ability for generator functions to
495 use it to return a value.
496
497 .. versionchanged:: 3.5
498 Introduced the RuntimeError transformation via
499 ``from __future__ import generator_stop``, see :pep:`479`.
500
501 .. versionchanged:: 3.7
502 Enable :pep:`479` for all code by default: a :exc:`StopIteration`
503 error raised in a generator is transformed into a :exc:`RuntimeError`.
504
505 .. exception:: StopAsyncIteration
506
507 Must be raised by :meth:`~object.__anext__` method of an
508 :term:`asynchronous iterator` object to stop the iteration.
509
510 .. versionadded:: 3.5
511
512 .. exception:: SyntaxError(message, details)
513
514 Raised when the parser encounters a syntax error. This may occur in an
515 :keyword:`import` statement, in a call to the built-in functions
516 :func:`compile`, :func:`exec`,
517 or :func:`eval`, or when reading the initial script or standard input
518 (also interactively).
519
520 The :func:`str` of the exception instance returns only the error message.
521 Details is a tuple whose members are also available as separate attributes.
522
523 .. attribute:: filename
524
525 The name of the file the syntax error occurred in.
526
527 .. attribute:: lineno
528
529 Which line number in the file the error occurred in. This is
530 1-indexed: the first line in the file has a ``lineno`` of 1.
531
532 .. attribute:: offset
533
534 The column in the line where the error occurred. This is
535 1-indexed: the first character in the line has an ``offset`` of 1.
536
537 .. attribute:: text
538
539 The source code text involved in the error.
540
541 .. attribute:: end_lineno
542
543 Which line number in the file the error occurred ends in. This is
544 1-indexed: the first line in the file has a ``lineno`` of 1.
545
546 .. attribute:: end_offset
547
548 The column in the end line where the error occurred finishes. This is
549 1-indexed: the first character in the line has an ``offset`` of 1.
550
551 For errors in f-string fields, the message is prefixed by "f-string: "
552 and the offsets are offsets in a text constructed from the replacement
553 expression. For example, compiling f'Bad {a b} field' results in this
554 args attribute: ('f-string: ...', ('', 1, 2, '(a b)\n', 1, 5)).
555
556 .. versionchanged:: 3.10
557 Added the :attr:`end_lineno` and :attr:`end_offset` attributes.
558
559 .. exception:: IndentationError
560
561 Base class for syntax errors related to incorrect indentation. This is a
562 subclass of :exc:`SyntaxError`.
563
564
565 .. exception:: TabError
566
567 Raised when indentation contains an inconsistent use of tabs and spaces.
568 This is a subclass of :exc:`IndentationError`.
569
570
571 .. exception:: SystemError
572
573 Raised when the interpreter finds an internal error, but the situation does not
574 look so serious to cause it to abandon all hope. The associated value is a
575 string indicating what went wrong (in low-level terms). In :term:`CPython`,
576 this could be raised by incorrectly using Python's C API, such as returning
577 a ``NULL`` value without an exception set.
578
579 If you're confident that this exception wasn't your fault, or the fault of
580 a package you're using, you should report this to the author or maintainer
581 of your Python interpreter.
582 Be sure to report the version of the Python interpreter (``sys.version``; it is
583 also printed at the start of an interactive Python session), the exact error
584 message (the exception's associated value) and if possible the source of the
585 program that triggered the error.
586
587
588 .. exception:: SystemExit
589
590 This exception is raised by the :func:`sys.exit` function. It inherits from
591 :exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally
592 caught by code that catches :exc:`Exception`. This allows the exception to
593 properly propagate up and cause the interpreter to exit. When it is not
594 handled, the Python interpreter exits; no stack traceback is printed. The
595 constructor accepts the same optional argument passed to :func:`sys.exit`.
596 If the value is an integer, it specifies the system exit status (passed to
597 C's :c:func:`!exit` function); if it is ``None``, the exit status is zero; if
598 it has another type (such as a string), the object's value is printed and
599 the exit status is one.
600
601 A call to :func:`sys.exit` is translated into an exception so that clean-up
602 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
603 executed, and so that a debugger can execute a script without running the risk
604 of losing control. The :func:`os._exit` function can be used if it is
605 absolutely positively necessary to exit immediately (for example, in the child
606 process after a call to :func:`os.fork`).
607
608 .. attribute:: code
609
610 The exit status or error message that is passed to the constructor.
611 (Defaults to ``None``.)
612
613
614 .. exception:: TypeError
615
616 Raised when an operation or function is applied to an object of inappropriate
617 type. The associated value is a string giving details about the type mismatch.
618
619 This exception may be raised by user code to indicate that an attempted
620 operation on an object is not supported, and is not meant to be. If an object
621 is meant to support a given operation but has not yet provided an
622 implementation, :exc:`NotImplementedError` is the proper exception to raise.
623
624 Passing arguments of the wrong type (e.g. passing a :class:`list` when an
625 :class:`int` is expected) should result in a :exc:`TypeError`, but passing
626 arguments with the wrong value (e.g. a number outside expected boundaries)
627 should result in a :exc:`ValueError`.
628
629 .. exception:: UnboundLocalError
630
631 Raised when a reference is made to a local variable in a function or method, but
632 no value has been bound to that variable. This is a subclass of
633 :exc:`NameError`.
634
635
636 .. exception:: UnicodeError
637
638 Raised when a Unicode-related encoding or decoding error occurs. It is a
639 subclass of :exc:`ValueError`.
640
641 :exc:`UnicodeError` has attributes that describe the encoding or decoding
642 error. For example, ``err.object[err.start:err.end]`` gives the particular
643 invalid input that the codec failed on.
644
645 .. attribute:: encoding
646
647 The name of the encoding that raised the error.
648
649 .. attribute:: reason
650
651 A string describing the specific codec error.
652
653 .. attribute:: object
654
655 The object the codec was attempting to encode or decode.
656
657 .. attribute:: start
658
659 The first index of invalid data in :attr:`object`.
660
661 .. attribute:: end
662
663 The index after the last invalid data in :attr:`object`.
664
665
666 .. exception:: UnicodeEncodeError
667
668 Raised when a Unicode-related error occurs during encoding. It is a subclass of
669 :exc:`UnicodeError`.
670
671
672 .. exception:: UnicodeDecodeError
673
674 Raised when a Unicode-related error occurs during decoding. It is a subclass of
675 :exc:`UnicodeError`.
676
677
678 .. exception:: UnicodeTranslateError
679
680 Raised when a Unicode-related error occurs during translating. It is a subclass
681 of :exc:`UnicodeError`.
682
683
684 .. exception:: ValueError
685
686 Raised when an operation or function receives an argument that has the
687 right type but an inappropriate value, and the situation is not described by a
688 more precise exception such as :exc:`IndexError`.
689
690
691 .. exception:: ZeroDivisionError
692
693 Raised when the second argument of a division or modulo operation is zero. The
694 associated value is a string indicating the type of the operands and the
695 operation.
696
697
698 The following exceptions are kept for compatibility with previous versions;
699 starting from Python 3.3, they are aliases of :exc:`OSError`.
700
701 .. exception:: EnvironmentError
702
703 .. exception:: IOError
704
705 .. exception:: WindowsError
706
707 Only available on Windows.
708
709
710 OS exceptions
711 ^^^^^^^^^^^^^
712
713 The following exceptions are subclasses of :exc:`OSError`, they get raised
714 depending on the system error code.
715
716 .. exception:: BlockingIOError
717
718 Raised when an operation would block on an object (e.g. socket) set
719 for non-blocking operation.
720 Corresponds to :c:data:`errno` :py:const:`~errno.EAGAIN`, :py:const:`~errno.EALREADY`,
721 :py:const:`~errno.EWOULDBLOCK` and :py:const:`~errno.EINPROGRESS`.
722
723 In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have
724 one more attribute:
725
726 .. attribute:: characters_written
727
728 An integer containing the number of **bytes** written to the stream
729 before it blocked. This attribute is available when using the
730 buffered I/O classes from the :mod:`io` module.
731
732 .. exception:: ChildProcessError
733
734 Raised when an operation on a child process failed.
735 Corresponds to :c:data:`errno` :py:const:`~errno.ECHILD`.
736
737 .. exception:: ConnectionError
738
739 A base class for connection-related issues.
740
741 Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
742 :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
743
744 .. exception:: BrokenPipeError
745
746 A subclass of :exc:`ConnectionError`, raised when trying to write on a
747 pipe while the other end has been closed, or trying to write on a socket
748 which has been shutdown for writing.
749 Corresponds to :c:data:`errno` :py:const:`~errno.EPIPE` and :py:const:`~errno.ESHUTDOWN`.
750
751 .. exception:: ConnectionAbortedError
752
753 A subclass of :exc:`ConnectionError`, raised when a connection attempt
754 is aborted by the peer.
755 Corresponds to :c:data:`errno` :py:const:`~errno.ECONNABORTED`.
756
757 .. exception:: ConnectionRefusedError
758
759 A subclass of :exc:`ConnectionError`, raised when a connection attempt
760 is refused by the peer.
761 Corresponds to :c:data:`errno` :py:const:`~errno.ECONNREFUSED`.
762
763 .. exception:: ConnectionResetError
764
765 A subclass of :exc:`ConnectionError`, raised when a connection is
766 reset by the peer.
767 Corresponds to :c:data:`errno` :py:const:`~errno.ECONNRESET`.
768
769 .. exception:: FileExistsError
770
771 Raised when trying to create a file or directory which already exists.
772 Corresponds to :c:data:`errno` :py:const:`~errno.EEXIST`.
773
774 .. exception:: FileNotFoundError
775
776 Raised when a file or directory is requested but doesn't exist.
777 Corresponds to :c:data:`errno` :py:const:`~errno.ENOENT`.
778
779 .. exception:: InterruptedError
780
781 Raised when a system call is interrupted by an incoming signal.
782 Corresponds to :c:data:`errno` :py:const:`~errno.EINTR`.
783
784 .. versionchanged:: 3.5
785 Python now retries system calls when a syscall is interrupted by a
786 signal, except if the signal handler raises an exception (see :pep:`475`
787 for the rationale), instead of raising :exc:`InterruptedError`.
788
789 .. exception:: IsADirectoryError
790
791 Raised when a file operation (such as :func:`os.remove`) is requested
792 on a directory.
793 Corresponds to :c:data:`errno` :py:const:`~errno.EISDIR`.
794
795 .. exception:: NotADirectoryError
796
797 Raised when a directory operation (such as :func:`os.listdir`) is requested on
798 something which is not a directory. On most POSIX platforms, it may also be
799 raised if an operation attempts to open or traverse a non-directory file as if
800 it were a directory.
801 Corresponds to :c:data:`errno` :py:const:`~errno.ENOTDIR`.
802
803 .. exception:: PermissionError
804
805 Raised when trying to run an operation without the adequate access
806 rights - for example filesystem permissions.
807 Corresponds to :c:data:`errno` :py:const:`~errno.EACCES`,
808 :py:const:`~errno.EPERM`, and :py:const:`~errno.ENOTCAPABLE`.
809
810 .. versionchanged:: 3.11.1
811 WASI's :py:const:`~errno.ENOTCAPABLE` is now mapped to
812 :exc:`PermissionError`.
813
814 .. exception:: ProcessLookupError
815
816 Raised when a given process doesn't exist.
817 Corresponds to :c:data:`errno` :py:const:`~errno.ESRCH`.
818
819 .. exception:: TimeoutError
820
821 Raised when a system function timed out at the system level.
822 Corresponds to :c:data:`errno` :py:const:`~errno.ETIMEDOUT`.
823
824 .. versionadded:: 3.3
825 All the above :exc:`OSError` subclasses were added.
826
827
828 .. seealso::
829
830 :pep:`3151` - Reworking the OS and IO exception hierarchy
831
832
833 .. _warning-categories-as-exceptions:
834
835 Warnings
836 --------
837
838 The following exceptions are used as warning categories; see the
839 :ref:`warning-categories` documentation for more details.
840
841 .. exception:: Warning
842
843 Base class for warning categories.
844
845
846 .. exception:: UserWarning
847
848 Base class for warnings generated by user code.
849
850
851 .. exception:: DeprecationWarning
852
853 Base class for warnings about deprecated features when those warnings are
854 intended for other Python developers.
855
856 Ignored by the default warning filters, except in the ``__main__`` module
857 (:pep:`565`). Enabling the :ref:`Python Development Mode <devmode>` shows
858 this warning.
859
860 The deprecation policy is described in :pep:`387`.
861
862
863 .. exception:: PendingDeprecationWarning
864
865 Base class for warnings about features which are obsolete and
866 expected to be deprecated in the future, but are not deprecated
867 at the moment.
868
869 This class is rarely used as emitting a warning about a possible
870 upcoming deprecation is unusual, and :exc:`DeprecationWarning`
871 is preferred for already active deprecations.
872
873 Ignored by the default warning filters. Enabling the :ref:`Python
874 Development Mode <devmode>` shows this warning.
875
876 The deprecation policy is described in :pep:`387`.
877
878
879 .. exception:: SyntaxWarning
880
881 Base class for warnings about dubious syntax.
882
883 This warning is typically emitted when compiling Python source code, and usually won't be reported
884 when running already compiled code.
885
886
887 .. exception:: RuntimeWarning
888
889 Base class for warnings about dubious runtime behavior.
890
891
892 .. exception:: FutureWarning
893
894 Base class for warnings about deprecated features when those warnings are
895 intended for end users of applications that are written in Python.
896
897
898 .. exception:: ImportWarning
899
900 Base class for warnings about probable mistakes in module imports.
901
902 Ignored by the default warning filters. Enabling the :ref:`Python
903 Development Mode <devmode>` shows this warning.
904
905
906 .. exception:: UnicodeWarning
907
908 Base class for warnings related to Unicode.
909
910
911 .. exception:: EncodingWarning
912
913 Base class for warnings related to encodings.
914
915 See :ref:`io-encoding-warning` for details.
916
917 .. versionadded:: 3.10
918
919
920 .. exception:: BytesWarning
921
922 Base class for warnings related to :class:`bytes` and :class:`bytearray`.
923
924
925 .. exception:: ResourceWarning
926
927 Base class for warnings related to resource usage.
928
929 Ignored by the default warning filters. Enabling the :ref:`Python
930 Development Mode <devmode>` shows this warning.
931
932 .. versionadded:: 3.2
933
934
935 .. _lib-exception-groups:
936
937 Exception groups
938 ----------------
939
940 The following are used when it is necessary to raise multiple unrelated
941 exceptions. They are part of the exception hierarchy so they can be
942 handled with :keyword:`except` like all other exceptions. In addition,
943 they are recognised by :keyword:`except*<except_star>`, which matches
944 their subgroups based on the types of the contained exceptions.
945
946 .. exception:: ExceptionGroup(msg, excs)
947 .. exception:: BaseExceptionGroup(msg, excs)
948
949 Both of these exception types wrap the exceptions in the sequence ``excs``.
950 The ``msg`` parameter must be a string. The difference between the two
951 classes is that :exc:`BaseExceptionGroup` extends :exc:`BaseException` and
952 it can wrap any exception, while :exc:`ExceptionGroup` extends :exc:`Exception`
953 and it can only wrap subclasses of :exc:`Exception`. This design is so that
954 ``except Exception`` catches an :exc:`ExceptionGroup` but not
955 :exc:`BaseExceptionGroup`.
956
957 The :exc:`BaseExceptionGroup` constructor returns an :exc:`ExceptionGroup`
958 rather than a :exc:`BaseExceptionGroup` if all contained exceptions are
959 :exc:`Exception` instances, so it can be used to make the selection
960 automatic. The :exc:`ExceptionGroup` constructor, on the other hand,
961 raises a :exc:`TypeError` if any contained exception is not an
962 :exc:`Exception` subclass.
963
964 Exception groups are :ref:`generic <generics>` over the type of their
965 contained exceptions.
966
967 .. impl-detail::
968
969 The ``excs`` parameter may be any sequence, but lists and tuples are
970 specifically processed more efficiently here. For optimal performance,
971 pass a tuple as ``excs``.
972
973 .. attribute:: message
974
975 The ``msg`` argument to the constructor. This is a read-only attribute.
976
977 .. attribute:: exceptions
978
979 A tuple of the exceptions in the ``excs`` sequence given to the
980 constructor. This is a read-only attribute.
981
982 .. method:: subgroup(condition)
983
984 Returns an exception group that contains only the exceptions from the
985 current group that match *condition*, or ``None`` if the result is empty.
986
987 The condition can be an exception type or tuple of exception types, in which
988 case each exception is checked for a match using the same check that is used
989 in an ``except`` clause. The condition can also be a callable (other than
990 a type object) that accepts an exception as its single argument and returns
991 true for the exceptions that should be in the subgroup.
992
993 The nesting structure of the current exception is preserved in the result,
994 as are the values of its :attr:`message`,
995 :attr:`~BaseException.__traceback__`, :attr:`~BaseException.__cause__`,
996 :attr:`~BaseException.__context__` and
997 :attr:`~BaseException.__notes__` fields.
998 Empty nested groups are omitted from the result.
999
1000 The condition is checked for all exceptions in the nested exception group,
1001 including the top-level and any nested exception groups. If the condition is
1002 true for such an exception group, it is included in the result in full.
1003
1004 .. versionadded:: 3.13
1005 ``condition`` can be any callable which is not a type object.
1006
1007 .. method:: split(condition)
1008
1009 Like :meth:`subgroup`, but returns the pair ``(match, rest)`` where ``match``
1010 is ``subgroup(condition)`` and ``rest`` is the remaining non-matching
1011 part.
1012
1013 .. method:: derive(excs)
1014
1015 Returns an exception group with the same :attr:`message`, but which
1016 wraps the exceptions in ``excs``.
1017
1018 This method is used by :meth:`subgroup` and :meth:`split`, which
1019 are used in various contexts to break up an exception group. A
1020 subclass needs to override it in order to make :meth:`subgroup`
1021 and :meth:`split` return instances of the subclass rather
1022 than :exc:`ExceptionGroup`.
1023
1024 :meth:`subgroup` and :meth:`split` copy the
1025 :attr:`~BaseException.__traceback__`,
1026 :attr:`~BaseException.__cause__`, :attr:`~BaseException.__context__` and
1027 :attr:`~BaseException.__notes__` fields from
1028 the original exception group to the one returned by :meth:`derive`, so
1029 these fields do not need to be updated by :meth:`derive`.
1030
1031 .. doctest::
1032
1033 >>> class MyGroup(ExceptionGroup):
1034 ... def derive(self, excs):
1035 ... return MyGroup(self.message, excs)
1036 ...
1037 >>> e = MyGroup("eg", [ValueError(1), TypeError(2)])
1038 >>> e.add_note("a note")
1039 >>> e.__context__ = Exception("context")
1040 >>> e.__cause__ = Exception("cause")
1041 >>> try:
1042 ... raise e
1043 ... except Exception as e:
1044 ... exc = e
1045 ...
1046 >>> match, rest = exc.split(ValueError)
1047 >>> exc, exc.__context__, exc.__cause__, exc.__notes__
1048 (MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
1049 >>> match, match.__context__, match.__cause__, match.__notes__
1050 (MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note'])
1051 >>> rest, rest.__context__, rest.__cause__, rest.__notes__
1052 (MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
1053 >>> exc.__traceback__ is match.__traceback__ is rest.__traceback__
1054 True
1055
1056
1057 Note that :exc:`BaseExceptionGroup` defines :meth:`~object.__new__`, so
1058 subclasses that need a different constructor signature need to
1059 override that rather than :meth:`~object.__init__`. For example, the following
1060 defines an exception group subclass which accepts an exit_code and
1061 constructs the group's message from it. ::
1062
1063 class Errors(ExceptionGroup):
1064 def __new__(cls, errors, exit_code):
1065 self = super().__new__(Errors, f"exit code: {exit_code}", errors)
1066 self.exit_code = exit_code
1067 return self
1068
1069 def derive(self, excs):
1070 return Errors(excs, self.exit_code)
1071
1072 Like :exc:`ExceptionGroup`, any subclass of :exc:`BaseExceptionGroup` which
1073 is also a subclass of :exc:`Exception` can only wrap instances of
1074 :exc:`Exception`.
1075
1076 .. versionadded:: 3.11
1077
1078
1079 Exception hierarchy
1080 -------------------
1081
1082 The class hierarchy for built-in exceptions is:
1083
1084 .. literalinclude:: ../../Lib/test/exception_hierarchy.txt
1085 :language: text