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