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