1.. highlight:: c 2 3 4.. _exceptionhandling: 5 6****************** 7Exception Handling 8****************** 9 10The functions described in this chapter will let you handle and raise Python 11exceptions. It is important to understand some of the basics of Python 12exception handling. It works somewhat like the POSIX :c:data:`errno` variable: 13there is a global indicator (per thread) of the last error that occurred. Most 14C API functions don't clear this on success, but will set it to indicate the 15cause of the error on failure. Most C API functions also return an error 16indicator, usually ``NULL`` if they are supposed to return a pointer, or ``-1`` 17if they return an integer (exception: the ``PyArg_*`` functions 18return ``1`` for success and ``0`` for failure). 19 20Concretely, the error indicator consists of three object pointers: the 21exception's type, the exception's value, and the traceback object. Any 22of those pointers can be ``NULL`` if non-set (although some combinations are 23forbidden, for example you can't have a non-``NULL`` traceback if the exception 24type is ``NULL``). 25 26When a function must fail because some function it called failed, it generally 27doesn't set the error indicator; the function it called already set it. It is 28responsible for either handling the error and clearing the exception or 29returning after cleaning up any resources it holds (such as object references or 30memory allocations); it should *not* continue normally if it is not prepared to 31handle the error. If returning due to an error, it is important to indicate to 32the caller that an error has been set. If the error is not handled or carefully 33propagated, additional calls into the Python/C API may not behave as intended 34and may fail in mysterious ways. 35 36.. note:: 37 The error indicator is **not** the result of :func:`sys.exc_info`. 38 The former corresponds to an exception that is not yet caught (and is 39 therefore still propagating), while the latter returns an exception after 40 it is caught (and has therefore stopped propagating). 41 42 43Printing and clearing 44===================== 45 46 47.. c:function:: void PyErr_Clear() 48 49 Clear the error indicator. If the error indicator is not set, there is no 50 effect. 51 52 53.. c:function:: void PyErr_PrintEx(int set_sys_last_vars) 54 55 Print a standard traceback to ``sys.stderr`` and clear the error indicator. 56 **Unless** the error is a ``SystemExit``, in that case no traceback is 57 printed and the Python process will exit with the error code specified by 58 the ``SystemExit`` instance. 59 60 Call this function **only** when the error indicator is set. Otherwise it 61 will cause a fatal error! 62 63 If *set_sys_last_vars* is nonzero, the variable :data:`sys.last_exc` is 64 set to the printed exception. For backwards compatibility, the 65 deprecated variables :data:`sys.last_type`, :data:`sys.last_value` and 66 :data:`sys.last_traceback` are also set to the type, value and traceback 67 of this exception, respectively. 68 69 .. versionchanged:: 3.12 70 The setting of :data:`sys.last_exc` was added. 71 72 73.. c:function:: void PyErr_Print() 74 75 Alias for ``PyErr_PrintEx(1)``. 76 77 78.. c:function:: void PyErr_WriteUnraisable(PyObject *obj) 79 80 Call :func:`sys.unraisablehook` using the current exception and *obj* 81 argument. 82 83 This utility function prints a warning message to ``sys.stderr`` when an 84 exception has been set but it is impossible for the interpreter to actually 85 raise the exception. It is used, for example, when an exception occurs in an 86 :meth:`~object.__del__` method. 87 88 The function is called with a single argument *obj* that identifies the context 89 in which the unraisable exception occurred. If possible, 90 the repr of *obj* will be printed in the warning message. 91 If *obj* is ``NULL``, only the traceback is printed. 92 93 An exception must be set when calling this function. 94 95 .. versionchanged:: 3.4 96 Print a traceback. Print only traceback if *obj* is ``NULL``. 97 98 .. versionchanged:: 3.8 99 Use :func:`sys.unraisablehook`. 100 101 102.. c:function:: void PyErr_FormatUnraisable(const char *format, ...) 103 104 Similar to :c:func:`PyErr_WriteUnraisable`, but the *format* and subsequent 105 parameters help format the warning message; they have the same meaning and 106 values as in :c:func:`PyUnicode_FromFormat`. 107 ``PyErr_WriteUnraisable(obj)`` is roughly equivalent to 108 ``PyErr_FormatUnraisable("Exception ignored in: %R", obj)``. 109 If *format* is ``NULL``, only the traceback is printed. 110 111 .. versionadded:: 3.13 112 113 114.. c:function:: void PyErr_DisplayException(PyObject *exc) 115 116 Print the standard traceback display of ``exc`` to ``sys.stderr``, including 117 chained exceptions and notes. 118 119 .. versionadded:: 3.12 120 121 122Raising exceptions 123================== 124 125These functions help you set the current thread's error indicator. 126For convenience, some of these functions will always return a 127``NULL`` pointer for use in a ``return`` statement. 128 129 130.. c:function:: void PyErr_SetString(PyObject *type, const char *message) 131 132 This is the most common way to set the error indicator. The first argument 133 specifies the exception type; it is normally one of the standard exceptions, 134 e.g. :c:data:`PyExc_RuntimeError`. You need not create a new 135 :term:`strong reference` to it (e.g. with :c:func:`Py_INCREF`). 136 The second argument is an error message; it is decoded from ``'utf-8'``. 137 138 139.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value) 140 141 This function is similar to :c:func:`PyErr_SetString` but lets you specify an 142 arbitrary Python object for the "value" of the exception. 143 144 145.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...) 146 147 This function sets the error indicator and returns ``NULL``. *exception* 148 should be a Python exception class. The *format* and subsequent 149 parameters help format the error message; they have the same meaning and 150 values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded 151 string. 152 153 154.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs) 155 156 Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather 157 than a variable number of arguments. 158 159 .. versionadded:: 3.5 160 161 162.. c:function:: void PyErr_SetNone(PyObject *type) 163 164 This is a shorthand for ``PyErr_SetObject(type, Py_None)``. 165 166 167.. c:function:: int PyErr_BadArgument() 168 169 This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where 170 *message* indicates that a built-in operation was invoked with an illegal 171 argument. It is mostly for internal use. 172 173 174.. c:function:: PyObject* PyErr_NoMemory() 175 176 This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns ``NULL`` 177 so an object allocation function can write ``return PyErr_NoMemory();`` when it 178 runs out of memory. 179 180 181.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type) 182 183 .. index:: single: strerror (C function) 184 185 This is a convenience function to raise an exception when a C library function 186 has returned an error and set the C variable :c:data:`errno`. It constructs a 187 tuple object whose first item is the integer :c:data:`errno` value and whose 188 second item is the corresponding error message (gotten from :c:func:`!strerror`), 189 and then calls ``PyErr_SetObject(type, object)``. On Unix, when the 190 :c:data:`errno` value is :c:macro:`!EINTR`, indicating an interrupted system call, 191 this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator, 192 leaves it set to that. The function always returns ``NULL``, so a wrapper 193 function around a system call can write ``return PyErr_SetFromErrno(type);`` 194 when the system call returns an error. 195 196 197.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject) 198 199 Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if 200 *filenameObject* is not ``NULL``, it is passed to the constructor of *type* as 201 a third parameter. In the case of :exc:`OSError` exception, 202 this is used to define the :attr:`!filename` attribute of the 203 exception instance. 204 205 206.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2) 207 208 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but takes a second 209 filename object, for raising errors when a function that takes two filenames 210 fails. 211 212 .. versionadded:: 3.4 213 214 215.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) 216 217 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename 218 is given as a C string. *filename* is decoded from the :term:`filesystem 219 encoding and error handler`. 220 221 222.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr) 223 224 This is a convenience function to raise :exc:`OSError`. If called with 225 *ierr* of ``0``, the error code returned by a call to :c:func:`!GetLastError` 226 is used instead. It calls the Win32 function :c:func:`!FormatMessage` to retrieve 227 the Windows description of error code given by *ierr* or :c:func:`!GetLastError`, 228 then it constructs a :exc:`OSError` object with the :attr:`~OSError.winerror` 229 attribute set to the error code, the :attr:`~OSError.strerror` attribute 230 set to the corresponding error message (gotten from 231 :c:func:`!FormatMessage`), and then calls ``PyErr_SetObject(PyExc_OSError, 232 object)``. This function always returns ``NULL``. 233 234 .. availability:: Windows. 235 236 237.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr) 238 239 Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter 240 specifying the exception type to be raised. 241 242 .. availability:: Windows. 243 244 245.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) 246 247 Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior 248 that if *filename* is not ``NULL``, it is decoded from the filesystem 249 encoding (:func:`os.fsdecode`) and passed to the constructor of 250 :exc:`OSError` as a third parameter to be used to define the 251 :attr:`!filename` attribute of the exception instance. 252 253 .. availability:: Windows. 254 255 256.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename) 257 258 Similar to :c:func:`PyErr_SetExcFromWindowsErr`, with the additional behavior 259 that if *filename* is not ``NULL``, it is passed to the constructor of 260 :exc:`OSError` as a third parameter to be used to define the 261 :attr:`!filename` attribute of the exception instance. 262 263 .. availability:: Windows. 264 265 266.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2) 267 268 Similar to :c:func:`PyErr_SetExcFromWindowsErrWithFilenameObject`, 269 but accepts a second filename object. 270 271 .. availability:: Windows. 272 273 .. versionadded:: 3.4 274 275 276.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename) 277 278 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional 279 parameter specifying the exception type to be raised. 280 281 .. availability:: Windows. 282 283 284.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path) 285 286 This is a convenience function to raise :exc:`ImportError`. *msg* will be 287 set as the exception's message string. *name* and *path*, both of which can 288 be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name`` 289 and ``path`` attributes. 290 291 .. versionadded:: 3.3 292 293 294.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path) 295 296 Much like :c:func:`PyErr_SetImportError` but this function allows for 297 specifying a subclass of :exc:`ImportError` to raise. 298 299 .. versionadded:: 3.6 300 301 302.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) 303 304 Set file, line, and offset information for the current exception. If the 305 current exception is not a :exc:`SyntaxError`, then it sets additional 306 attributes, which make the exception printing subsystem think the exception 307 is a :exc:`SyntaxError`. 308 309 .. versionadded:: 3.4 310 311 312.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset) 313 314 Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string 315 decoded from the :term:`filesystem encoding and error handler`. 316 317 .. versionadded:: 3.2 318 319 320.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno) 321 322 Like :c:func:`PyErr_SyntaxLocationEx`, but the *col_offset* parameter is 323 omitted. 324 325 326.. c:function:: void PyErr_BadInternalCall() 327 328 This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``, 329 where *message* indicates that an internal operation (e.g. a Python/C API 330 function) was invoked with an illegal argument. It is mostly for internal 331 use. 332 333 334Issuing warnings 335================ 336 337Use these functions to issue warnings from C code. They mirror similar 338functions exported by the Python :mod:`warnings` module. They normally 339print a warning message to *sys.stderr*; however, it is 340also possible that the user has specified that warnings are to be turned into 341errors, and in that case they will raise an exception. It is also possible that 342the functions raise an exception because of a problem with the warning machinery. 343The return value is ``0`` if no exception is raised, or ``-1`` if an exception 344is raised. (It is not possible to determine whether a warning message is 345actually printed, nor what the reason is for the exception; this is 346intentional.) If an exception is raised, the caller should do its normal 347exception handling (for example, :c:func:`Py_DECREF` owned references and return 348an error value). 349 350.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level) 351 352 Issue a warning message. The *category* argument is a warning category (see 353 below) or ``NULL``; the *message* argument is a UTF-8 encoded string. *stack_level* is a 354 positive number giving a number of stack frames; the warning will be issued from 355 the currently executing line of code in that stack frame. A *stack_level* of 1 356 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, 357 and so forth. 358 359 Warning categories must be subclasses of :c:data:`PyExc_Warning`; 360 :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`; 361 the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard 362 Python warning categories are available as global variables whose names are 363 enumerated at :ref:`standardwarningcategories`. 364 365 For information about warning control, see the documentation for the 366 :mod:`warnings` module and the :option:`-W` option in the command line 367 documentation. There is no C API for warning control. 368 369 370.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry) 371 372 Issue a warning message with explicit control over all warning attributes. This 373 is a straightforward wrapper around the Python function 374 :func:`warnings.warn_explicit`; see there for more information. The *module* 375 and *registry* arguments may be set to ``NULL`` to get the default effect 376 described there. 377 378 .. versionadded:: 3.4 379 380 381.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry) 382 383 Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and 384 *module* are UTF-8 encoded strings, and *filename* is decoded from the 385 :term:`filesystem encoding and error handler`. 386 387 388.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...) 389 390 Function similar to :c:func:`PyErr_WarnEx`, but use 391 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is 392 an ASCII-encoded string. 393 394 .. versionadded:: 3.2 395 396 397.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...) 398 399 Function similar to :c:func:`PyErr_WarnFormat`, but *category* is 400 :exc:`ResourceWarning` and it passes *source* to :class:`!warnings.WarningMessage`. 401 402 .. versionadded:: 3.6 403 404 405Querying the error indicator 406============================ 407 408.. c:function:: PyObject* PyErr_Occurred() 409 410 Test whether the error indicator is set. If set, return the exception *type* 411 (the first argument to the last call to one of the ``PyErr_Set*`` 412 functions or to :c:func:`PyErr_Restore`). If not set, return ``NULL``. You do not 413 own a reference to the return value, so you do not need to :c:func:`Py_DECREF` 414 it. 415 416 The caller must hold the GIL. 417 418 .. note:: 419 420 Do not compare the return value to a specific exception; use 421 :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could 422 easily fail since the exception may be an instance instead of a class, in the 423 case of a class exception, or it may be a subclass of the expected exception.) 424 425 426.. c:function:: int PyErr_ExceptionMatches(PyObject *exc) 427 428 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This 429 should only be called when an exception is actually set; a memory access 430 violation will occur if no exception has been raised. 431 432 433.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) 434 435 Return true if the *given* exception matches the exception type in *exc*. If 436 *exc* is a class object, this also returns true when *given* is an instance 437 of a subclass. If *exc* is a tuple, all exception types in the tuple (and 438 recursively in subtuples) are searched for a match. 439 440 441.. c:function:: PyObject *PyErr_GetRaisedException(void) 442 443 Return the exception currently being raised, clearing the error indicator at 444 the same time. Return ``NULL`` if the error indicator is not set. 445 446 This function is used by code that needs to catch exceptions, 447 or code that needs to save and restore the error indicator temporarily. 448 449 For example:: 450 451 { 452 PyObject *exc = PyErr_GetRaisedException(); 453 454 /* ... code that might produce other errors ... */ 455 456 PyErr_SetRaisedException(exc); 457 } 458 459 .. seealso:: :c:func:`PyErr_GetHandledException`, 460 to save the exception currently being handled. 461 462 .. versionadded:: 3.12 463 464 465.. c:function:: void PyErr_SetRaisedException(PyObject *exc) 466 467 Set *exc* as the exception currently being raised, 468 clearing the existing exception if one is set. 469 470 .. warning:: 471 472 This call steals a reference to *exc*, which must be a valid exception. 473 474 .. versionadded:: 3.12 475 476 477.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) 478 479 .. deprecated:: 3.12 480 481 Use :c:func:`PyErr_GetRaisedException` instead. 482 483 Retrieve the error indicator into three variables whose addresses are passed. 484 If the error indicator is not set, set all three variables to ``NULL``. If it is 485 set, it will be cleared and you own a reference to each object retrieved. The 486 value and traceback object may be ``NULL`` even when the type object is not. 487 488 .. note:: 489 490 This function is normally only used by legacy code that needs to catch 491 exceptions or save and restore the error indicator temporarily. 492 493 For example:: 494 495 { 496 PyObject *type, *value, *traceback; 497 PyErr_Fetch(&type, &value, &traceback); 498 499 /* ... code that might produce other errors ... */ 500 501 PyErr_Restore(type, value, traceback); 502 } 503 504 505.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) 506 507 .. deprecated:: 3.12 508 509 Use :c:func:`PyErr_SetRaisedException` instead. 510 511 Set the error indicator from the three objects, 512 *type*, *value*, and *traceback*, 513 clearing the existing exception if one is set. 514 If the objects are ``NULL``, the error 515 indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or 516 traceback. The exception type should be a class. Do not pass an invalid 517 exception type or value. (Violating these rules will cause subtle problems 518 later.) This call takes away a reference to each object: you must own a 519 reference to each object before the call and after the call you no longer own 520 these references. (If you don't understand this, don't use this function. I 521 warned you.) 522 523 .. note:: 524 525 This function is normally only used by legacy code that needs to 526 save and restore the error indicator temporarily. 527 Use :c:func:`PyErr_Fetch` to save the current error indicator. 528 529 530.. c:function:: void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb) 531 532 .. deprecated:: 3.12 533 534 Use :c:func:`PyErr_GetRaisedException` instead, 535 to avoid any possible de-normalization. 536 537 Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below 538 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is 539 not an instance of the same class. This function can be used to instantiate 540 the class in that case. If the values are already normalized, nothing happens. 541 The delayed normalization is implemented to improve performance. 542 543 .. note:: 544 545 This function *does not* implicitly set the 546 :attr:`~BaseException.__traceback__` 547 attribute on the exception value. If setting the traceback 548 appropriately is desired, the following additional snippet is needed:: 549 550 if (tb != NULL) { 551 PyException_SetTraceback(val, tb); 552 } 553 554 555.. c:function:: PyObject* PyErr_GetHandledException(void) 556 557 Retrieve the active exception instance, as would be returned by :func:`sys.exception`. 558 This refers to an exception that was *already caught*, not to an exception that was 559 freshly raised. Returns a new reference to the exception or ``NULL``. 560 Does not modify the interpreter's exception state. 561 562 .. note:: 563 564 This function is not normally used by code that wants to handle exceptions. 565 Rather, it can be used when code needs to save and restore the exception 566 state temporarily. Use :c:func:`PyErr_SetHandledException` to restore or 567 clear the exception state. 568 569 .. versionadded:: 3.11 570 571.. c:function:: void PyErr_SetHandledException(PyObject *exc) 572 573 Set the active exception, as known from ``sys.exception()``. This refers 574 to an exception that was *already caught*, not to an exception that was 575 freshly raised. 576 To clear the exception state, pass ``NULL``. 577 578 .. note:: 579 580 This function is not normally used by code that wants to handle exceptions. 581 Rather, it can be used when code needs to save and restore the exception 582 state temporarily. Use :c:func:`PyErr_GetHandledException` to get the exception 583 state. 584 585 .. versionadded:: 3.11 586 587.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) 588 589 Retrieve the old-style representation of the exception info, as known from 590 :func:`sys.exc_info`. This refers to an exception that was *already caught*, 591 not to an exception that was freshly raised. Returns new references for the 592 three objects, any of which may be ``NULL``. Does not modify the exception 593 info state. This function is kept for backwards compatibility. Prefer using 594 :c:func:`PyErr_GetHandledException`. 595 596 .. note:: 597 598 This function is not normally used by code that wants to handle exceptions. 599 Rather, it can be used when code needs to save and restore the exception 600 state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the 601 exception state. 602 603 .. versionadded:: 3.3 604 605 606.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback) 607 608 Set the exception info, as known from ``sys.exc_info()``. This refers 609 to an exception that was *already caught*, not to an exception that was 610 freshly raised. This function steals the references of the arguments. 611 To clear the exception state, pass ``NULL`` for all three arguments. 612 This function is kept for backwards compatibility. Prefer using 613 :c:func:`PyErr_SetHandledException`. 614 615 .. note:: 616 617 This function is not normally used by code that wants to handle exceptions. 618 Rather, it can be used when code needs to save and restore the exception 619 state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception 620 state. 621 622 .. versionadded:: 3.3 623 624 .. versionchanged:: 3.11 625 The ``type`` and ``traceback`` arguments are no longer used and 626 can be NULL. The interpreter now derives them from the exception 627 instance (the ``value`` argument). The function still steals 628 references of all three arguments. 629 630 631Signal Handling 632=============== 633 634 635.. c:function:: int PyErr_CheckSignals() 636 637 .. index:: 638 pair: module; signal 639 single: SIGINT (C macro) 640 single: KeyboardInterrupt (built-in exception) 641 642 This function interacts with Python's signal handling. 643 644 If the function is called from the main thread and under the main Python 645 interpreter, it checks whether a signal has been sent to the processes 646 and if so, invokes the corresponding signal handler. If the :mod:`signal` 647 module is supported, this can invoke a signal handler written in Python. 648 649 The function attempts to handle all pending signals, and then returns ``0``. 650 However, if a Python signal handler raises an exception, the error 651 indicator is set and the function returns ``-1`` immediately (such that 652 other pending signals may not have been handled yet: they will be on the 653 next :c:func:`PyErr_CheckSignals()` invocation). 654 655 If the function is called from a non-main thread, or under a non-main 656 Python interpreter, it does nothing and returns ``0``. 657 658 This function can be called by long-running C code that wants to 659 be interruptible by user requests (such as by pressing Ctrl-C). 660 661 .. note:: 662 The default Python signal handler for :c:macro:`!SIGINT` raises the 663 :exc:`KeyboardInterrupt` exception. 664 665 666.. c:function:: void PyErr_SetInterrupt() 667 668 .. index:: 669 pair: module; signal 670 single: SIGINT (C macro) 671 single: KeyboardInterrupt (built-in exception) 672 673 Simulate the effect of a :c:macro:`!SIGINT` signal arriving. 674 This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``. 675 676 .. note:: 677 This function is async-signal-safe. It can be called without 678 the :term:`GIL` and from a C signal handler. 679 680 681.. c:function:: int PyErr_SetInterruptEx(int signum) 682 683 .. index:: 684 pair: module; signal 685 single: KeyboardInterrupt (built-in exception) 686 687 Simulate the effect of a signal arriving. The next time 688 :c:func:`PyErr_CheckSignals` is called, the Python signal handler for 689 the given signal number will be called. 690 691 This function can be called by C code that sets up its own signal handling 692 and wants Python signal handlers to be invoked as expected when an 693 interruption is requested (for example when the user presses Ctrl-C 694 to interrupt an operation). 695 696 If the given signal isn't handled by Python (it was set to 697 :py:const:`signal.SIG_DFL` or :py:const:`signal.SIG_IGN`), it will be ignored. 698 699 If *signum* is outside of the allowed range of signal numbers, ``-1`` 700 is returned. Otherwise, ``0`` is returned. The error indicator is 701 never changed by this function. 702 703 .. note:: 704 This function is async-signal-safe. It can be called without 705 the :term:`GIL` and from a C signal handler. 706 707 .. versionadded:: 3.10 708 709 710.. c:function:: int PySignal_SetWakeupFd(int fd) 711 712 This utility function specifies a file descriptor to which the signal number 713 is written as a single byte whenever a signal is received. *fd* must be 714 non-blocking. It returns the previous such file descriptor. 715 716 The value ``-1`` disables the feature; this is the initial state. 717 This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any 718 error checking. *fd* should be a valid file descriptor. The function should 719 only be called from the main thread. 720 721 .. versionchanged:: 3.5 722 On Windows, the function now also supports socket handles. 723 724 725Exception Classes 726================= 727 728.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict) 729 730 This utility function creates and returns a new exception class. The *name* 731 argument must be the name of the new exception, a C string of the form 732 ``module.classname``. The *base* and *dict* arguments are normally ``NULL``. 733 This creates a class object derived from :exc:`Exception` (accessible in C as 734 :c:data:`PyExc_Exception`). 735 736 The :attr:`~type.__module__` attribute of the new class is set to the first part (up 737 to the last dot) of the *name* argument, and the class name is set to the last 738 part (after the last dot). The *base* argument can be used to specify alternate 739 base classes; it can either be only one class or a tuple of classes. The *dict* 740 argument can be used to specify a dictionary of class variables and methods. 741 742 743.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict) 744 745 Same as :c:func:`PyErr_NewException`, except that the new exception class can 746 easily be given a docstring: If *doc* is non-``NULL``, it will be used as the 747 docstring for the exception class. 748 749 .. versionadded:: 3.2 750 751 752Exception Objects 753================= 754 755.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex) 756 757 Return the traceback associated with the exception as a new reference, as 758 accessible from Python through the :attr:`~BaseException.__traceback__` 759 attribute. If there is no 760 traceback associated, this returns ``NULL``. 761 762 763.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb) 764 765 Set the traceback associated with the exception to *tb*. Use ``Py_None`` to 766 clear it. 767 768 769.. c:function:: PyObject* PyException_GetContext(PyObject *ex) 770 771 Return the context (another exception instance during whose handling *ex* was 772 raised) associated with the exception as a new reference, as accessible from 773 Python through the :attr:`~BaseException.__context__` attribute. 774 If there is no context associated, this returns ``NULL``. 775 776 777.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx) 778 779 Set the context associated with the exception to *ctx*. Use ``NULL`` to clear 780 it. There is no type check to make sure that *ctx* is an exception instance. 781 This steals a reference to *ctx*. 782 783 784.. c:function:: PyObject* PyException_GetCause(PyObject *ex) 785 786 Return the cause (either an exception instance, or ``None``, 787 set by ``raise ... from ...``) associated with the exception as a new 788 reference, as accessible from Python through the 789 :attr:`~BaseException.__cause__` attribute. 790 791 792.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause) 793 794 Set the cause associated with the exception to *cause*. Use ``NULL`` to clear 795 it. There is no type check to make sure that *cause* is either an exception 796 instance or ``None``. This steals a reference to *cause*. 797 798 The :attr:`~BaseException.__suppress_context__` attribute is implicitly set 799 to ``True`` by this function. 800 801 802.. c:function:: PyObject* PyException_GetArgs(PyObject *ex) 803 804 Return :attr:`~BaseException.args` of exception *ex*. 805 806 807.. c:function:: void PyException_SetArgs(PyObject *ex, PyObject *args) 808 809 Set :attr:`~BaseException.args` of exception *ex* to *args*. 810 811.. c:function:: PyObject* PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs) 812 813 Implement part of the interpreter's implementation of :keyword:`!except*`. 814 *orig* is the original exception that was caught, and *excs* is the list of 815 the exceptions that need to be raised. This list contains the unhandled 816 part of *orig*, if any, as well as the exceptions that were raised from the 817 :keyword:`!except*` clauses (so they have a different traceback from *orig*) and 818 those that were reraised (and have the same traceback as *orig*). 819 Return the :exc:`ExceptionGroup` that needs to be reraised in the end, or 820 ``None`` if there is nothing to reraise. 821 822 .. versionadded:: 3.12 823 824.. _unicodeexceptions: 825 826Unicode Exception Objects 827========================= 828 829The following functions are used to create and modify Unicode exceptions from C. 830 831.. c:function:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) 832 833 Create a :class:`UnicodeDecodeError` object with the attributes *encoding*, 834 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are 835 UTF-8 encoded strings. 836 837.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc) 838 PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc) 839 840 Return the *encoding* attribute of the given exception object. 841 842.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc) 843 PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc) 844 PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc) 845 846 Return the *object* attribute of the given exception object. 847 848.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) 849 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) 850 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) 851 852 Get the *start* attribute of the given exception object and place it into 853 *\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` on 854 failure. 855 856.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start) 857 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start) 858 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start) 859 860 Set the *start* attribute of the given exception object to *start*. Return 861 ``0`` on success, ``-1`` on failure. 862 863.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end) 864 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end) 865 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end) 866 867 Get the *end* attribute of the given exception object and place it into 868 *\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on 869 failure. 870 871.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end) 872 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end) 873 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end) 874 875 Set the *end* attribute of the given exception object to *end*. Return ``0`` 876 on success, ``-1`` on failure. 877 878.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc) 879 PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc) 880 PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc) 881 882 Return the *reason* attribute of the given exception object. 883 884.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason) 885 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason) 886 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason) 887 888 Set the *reason* attribute of the given exception object to *reason*. Return 889 ``0`` on success, ``-1`` on failure. 890 891 892.. _recursion: 893 894Recursion Control 895================= 896 897These two functions provide a way to perform safe recursive calls at the C 898level, both in the core and in extension modules. They are needed if the 899recursive code does not necessarily invoke Python code (which tracks its 900recursion depth automatically). 901They are also not needed for *tp_call* implementations 902because the :ref:`call protocol <call>` takes care of recursion handling. 903 904.. c:function:: int Py_EnterRecursiveCall(const char *where) 905 906 Marks a point where a recursive C-level call is about to be performed. 907 908 If :c:macro:`!USE_STACKCHECK` is defined, this function checks if the OS 909 stack overflowed using :c:func:`PyOS_CheckStack`. If this is the case, it 910 sets a :exc:`MemoryError` and returns a nonzero value. 911 912 The function then checks if the recursion limit is reached. If this is the 913 case, a :exc:`RecursionError` is set and a nonzero value is returned. 914 Otherwise, zero is returned. 915 916 *where* should be a UTF-8 encoded string such as ``" in instance check"`` to 917 be concatenated to the :exc:`RecursionError` message caused by the recursion 918 depth limit. 919 920 .. versionchanged:: 3.9 921 This function is now also available in the :ref:`limited API <limited-c-api>`. 922 923.. c:function:: void Py_LeaveRecursiveCall(void) 924 925 Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each 926 *successful* invocation of :c:func:`Py_EnterRecursiveCall`. 927 928 .. versionchanged:: 3.9 929 This function is now also available in the :ref:`limited API <limited-c-api>`. 930 931Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires 932special recursion handling. In addition to protecting the stack, 933:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The 934following two functions facilitate this functionality. Effectively, 935these are the C equivalent to :func:`reprlib.recursive_repr`. 936 937.. c:function:: int Py_ReprEnter(PyObject *object) 938 939 Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to 940 detect cycles. 941 942 If the object has already been processed, the function returns a 943 positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation 944 should return a string object indicating a cycle. As examples, 945 :class:`dict` objects return ``{...}`` and :class:`list` objects 946 return ``[...]``. 947 948 The function will return a negative integer if the recursion limit 949 is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should 950 typically return ``NULL``. 951 952 Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr` 953 implementation can continue normally. 954 955.. c:function:: void Py_ReprLeave(PyObject *object) 956 957 Ends a :c:func:`Py_ReprEnter`. Must be called once for each 958 invocation of :c:func:`Py_ReprEnter` that returns zero. 959 960 961.. _standardexceptions: 962 963Standard Exceptions 964=================== 965 966All standard Python exceptions are available as global variables whose names are 967``PyExc_`` followed by the Python exception name. These have the type 968:c:expr:`PyObject*`; they are all class objects. For completeness, here are all 969the variables: 970 971.. index:: 972 single: PyExc_BaseException (C var) 973 single: PyExc_Exception (C var) 974 single: PyExc_ArithmeticError (C var) 975 single: PyExc_AssertionError (C var) 976 single: PyExc_AttributeError (C var) 977 single: PyExc_BlockingIOError (C var) 978 single: PyExc_BrokenPipeError (C var) 979 single: PyExc_BufferError (C var) 980 single: PyExc_ChildProcessError (C var) 981 single: PyExc_ConnectionAbortedError (C var) 982 single: PyExc_ConnectionError (C var) 983 single: PyExc_ConnectionRefusedError (C var) 984 single: PyExc_ConnectionResetError (C var) 985 single: PyExc_EOFError (C var) 986 single: PyExc_FileExistsError (C var) 987 single: PyExc_FileNotFoundError (C var) 988 single: PyExc_FloatingPointError (C var) 989 single: PyExc_GeneratorExit (C var) 990 single: PyExc_ImportError (C var) 991 single: PyExc_IndentationError (C var) 992 single: PyExc_IndexError (C var) 993 single: PyExc_InterruptedError (C var) 994 single: PyExc_IsADirectoryError (C var) 995 single: PyExc_KeyError (C var) 996 single: PyExc_KeyboardInterrupt (C var) 997 single: PyExc_LookupError (C var) 998 single: PyExc_MemoryError (C var) 999 single: PyExc_ModuleNotFoundError (C var) 1000 single: PyExc_NameError (C var) 1001 single: PyExc_NotADirectoryError (C var) 1002 single: PyExc_NotImplementedError (C var) 1003 single: PyExc_OSError (C var) 1004 single: PyExc_OverflowError (C var) 1005 single: PyExc_PermissionError (C var) 1006 single: PyExc_ProcessLookupError (C var) 1007 single: PyExc_PythonFinalizationError (C var) 1008 single: PyExc_RecursionError (C var) 1009 single: PyExc_ReferenceError (C var) 1010 single: PyExc_RuntimeError (C var) 1011 single: PyExc_StopAsyncIteration (C var) 1012 single: PyExc_StopIteration (C var) 1013 single: PyExc_SyntaxError (C var) 1014 single: PyExc_SystemError (C var) 1015 single: PyExc_SystemExit (C var) 1016 single: PyExc_TabError (C var) 1017 single: PyExc_TimeoutError (C var) 1018 single: PyExc_TypeError (C var) 1019 single: PyExc_UnboundLocalError (C var) 1020 single: PyExc_UnicodeDecodeError (C var) 1021 single: PyExc_UnicodeEncodeError (C var) 1022 single: PyExc_UnicodeError (C var) 1023 single: PyExc_UnicodeTranslateError (C var) 1024 single: PyExc_ValueError (C var) 1025 single: PyExc_ZeroDivisionError (C var) 1026 1027+-----------------------------------------+---------------------------------+----------+ 1028| C Name | Python Name | Notes | 1029+=========================================+=================================+==========+ 1030| :c:data:`PyExc_BaseException` | :exc:`BaseException` | [1]_ | 1031+-----------------------------------------+---------------------------------+----------+ 1032| :c:data:`PyExc_Exception` | :exc:`Exception` | [1]_ | 1033+-----------------------------------------+---------------------------------+----------+ 1034| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | [1]_ | 1035+-----------------------------------------+---------------------------------+----------+ 1036| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | | 1037+-----------------------------------------+---------------------------------+----------+ 1038| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | | 1039+-----------------------------------------+---------------------------------+----------+ 1040| :c:data:`PyExc_BlockingIOError` | :exc:`BlockingIOError` | | 1041+-----------------------------------------+---------------------------------+----------+ 1042| :c:data:`PyExc_BrokenPipeError` | :exc:`BrokenPipeError` | | 1043+-----------------------------------------+---------------------------------+----------+ 1044| :c:data:`PyExc_BufferError` | :exc:`BufferError` | | 1045+-----------------------------------------+---------------------------------+----------+ 1046| :c:data:`PyExc_ChildProcessError` | :exc:`ChildProcessError` | | 1047+-----------------------------------------+---------------------------------+----------+ 1048| :c:data:`PyExc_ConnectionAbortedError` | :exc:`ConnectionAbortedError` | | 1049+-----------------------------------------+---------------------------------+----------+ 1050| :c:data:`PyExc_ConnectionError` | :exc:`ConnectionError` | | 1051+-----------------------------------------+---------------------------------+----------+ 1052| :c:data:`PyExc_ConnectionRefusedError` | :exc:`ConnectionRefusedError` | | 1053+-----------------------------------------+---------------------------------+----------+ 1054| :c:data:`PyExc_ConnectionResetError` | :exc:`ConnectionResetError` | | 1055+-----------------------------------------+---------------------------------+----------+ 1056| :c:data:`PyExc_EOFError` | :exc:`EOFError` | | 1057+-----------------------------------------+---------------------------------+----------+ 1058| :c:data:`PyExc_FileExistsError` | :exc:`FileExistsError` | | 1059+-----------------------------------------+---------------------------------+----------+ 1060| :c:data:`PyExc_FileNotFoundError` | :exc:`FileNotFoundError` | | 1061+-----------------------------------------+---------------------------------+----------+ 1062| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | | 1063+-----------------------------------------+---------------------------------+----------+ 1064| :c:data:`PyExc_GeneratorExit` | :exc:`GeneratorExit` | | 1065+-----------------------------------------+---------------------------------+----------+ 1066| :c:data:`PyExc_ImportError` | :exc:`ImportError` | | 1067+-----------------------------------------+---------------------------------+----------+ 1068| :c:data:`PyExc_IndentationError` | :exc:`IndentationError` | | 1069+-----------------------------------------+---------------------------------+----------+ 1070| :c:data:`PyExc_IndexError` | :exc:`IndexError` | | 1071+-----------------------------------------+---------------------------------+----------+ 1072| :c:data:`PyExc_InterruptedError` | :exc:`InterruptedError` | | 1073+-----------------------------------------+---------------------------------+----------+ 1074| :c:data:`PyExc_IsADirectoryError` | :exc:`IsADirectoryError` | | 1075+-----------------------------------------+---------------------------------+----------+ 1076| :c:data:`PyExc_KeyError` | :exc:`KeyError` | | 1077+-----------------------------------------+---------------------------------+----------+ 1078| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | | 1079+-----------------------------------------+---------------------------------+----------+ 1080| :c:data:`PyExc_LookupError` | :exc:`LookupError` | [1]_ | 1081+-----------------------------------------+---------------------------------+----------+ 1082| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | | 1083+-----------------------------------------+---------------------------------+----------+ 1084| :c:data:`PyExc_ModuleNotFoundError` | :exc:`ModuleNotFoundError` | | 1085+-----------------------------------------+---------------------------------+----------+ 1086| :c:data:`PyExc_NameError` | :exc:`NameError` | | 1087+-----------------------------------------+---------------------------------+----------+ 1088| :c:data:`PyExc_NotADirectoryError` | :exc:`NotADirectoryError` | | 1089+-----------------------------------------+---------------------------------+----------+ 1090| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | | 1091+-----------------------------------------+---------------------------------+----------+ 1092| :c:data:`PyExc_OSError` | :exc:`OSError` | [1]_ | 1093+-----------------------------------------+---------------------------------+----------+ 1094| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | | 1095+-----------------------------------------+---------------------------------+----------+ 1096| :c:data:`PyExc_PermissionError` | :exc:`PermissionError` | | 1097+-----------------------------------------+---------------------------------+----------+ 1098| :c:data:`PyExc_ProcessLookupError` | :exc:`ProcessLookupError` | | 1099+-----------------------------------------+---------------------------------+----------+ 1100| :c:data:`PyExc_PythonFinalizationError` | :exc:`PythonFinalizationError` | | 1101+-----------------------------------------+---------------------------------+----------+ 1102| :c:data:`PyExc_RecursionError` | :exc:`RecursionError` | | 1103+-----------------------------------------+---------------------------------+----------+ 1104| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | | 1105+-----------------------------------------+---------------------------------+----------+ 1106| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | | 1107+-----------------------------------------+---------------------------------+----------+ 1108| :c:data:`PyExc_StopAsyncIteration` | :exc:`StopAsyncIteration` | | 1109+-----------------------------------------+---------------------------------+----------+ 1110| :c:data:`PyExc_StopIteration` | :exc:`StopIteration` | | 1111+-----------------------------------------+---------------------------------+----------+ 1112| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | | 1113+-----------------------------------------+---------------------------------+----------+ 1114| :c:data:`PyExc_SystemError` | :exc:`SystemError` | | 1115+-----------------------------------------+---------------------------------+----------+ 1116| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | | 1117+-----------------------------------------+---------------------------------+----------+ 1118| :c:data:`PyExc_TabError` | :exc:`TabError` | | 1119+-----------------------------------------+---------------------------------+----------+ 1120| :c:data:`PyExc_TimeoutError` | :exc:`TimeoutError` | | 1121+-----------------------------------------+---------------------------------+----------+ 1122| :c:data:`PyExc_TypeError` | :exc:`TypeError` | | 1123+-----------------------------------------+---------------------------------+----------+ 1124| :c:data:`PyExc_UnboundLocalError` | :exc:`UnboundLocalError` | | 1125+-----------------------------------------+---------------------------------+----------+ 1126| :c:data:`PyExc_UnicodeDecodeError` | :exc:`UnicodeDecodeError` | | 1127+-----------------------------------------+---------------------------------+----------+ 1128| :c:data:`PyExc_UnicodeEncodeError` | :exc:`UnicodeEncodeError` | | 1129+-----------------------------------------+---------------------------------+----------+ 1130| :c:data:`PyExc_UnicodeError` | :exc:`UnicodeError` | | 1131+-----------------------------------------+---------------------------------+----------+ 1132| :c:data:`PyExc_UnicodeTranslateError` | :exc:`UnicodeTranslateError` | | 1133+-----------------------------------------+---------------------------------+----------+ 1134| :c:data:`PyExc_ValueError` | :exc:`ValueError` | | 1135+-----------------------------------------+---------------------------------+----------+ 1136| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | | 1137+-----------------------------------------+---------------------------------+----------+ 1138 1139.. versionadded:: 3.3 1140 :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`, 1141 :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`, 1142 :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`, 1143 :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`, 1144 :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`, 1145 :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`, 1146 :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError` 1147 and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`. 1148 1149.. versionadded:: 3.5 1150 :c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`. 1151 1152.. versionadded:: 3.6 1153 :c:data:`PyExc_ModuleNotFoundError`. 1154 1155These are compatibility aliases to :c:data:`PyExc_OSError`: 1156 1157.. index:: 1158 single: PyExc_EnvironmentError (C var) 1159 single: PyExc_IOError (C var) 1160 single: PyExc_WindowsError (C var) 1161 1162+-------------------------------------+----------+ 1163| C Name | Notes | 1164+=====================================+==========+ 1165| :c:data:`!PyExc_EnvironmentError` | | 1166+-------------------------------------+----------+ 1167| :c:data:`!PyExc_IOError` | | 1168+-------------------------------------+----------+ 1169| :c:data:`!PyExc_WindowsError` | [2]_ | 1170+-------------------------------------+----------+ 1171 1172.. versionchanged:: 3.3 1173 These aliases used to be separate exception types. 1174 1175Notes: 1176 1177.. [1] 1178 This is a base class for other standard exceptions. 1179 1180.. [2] 1181 Only defined on Windows; protect code that uses this by testing that the 1182 preprocessor macro ``MS_WINDOWS`` is defined. 1183 1184.. _standardwarningcategories: 1185 1186Standard Warning Categories 1187=========================== 1188 1189All standard Python warning categories are available as global variables whose 1190names are ``PyExc_`` followed by the Python exception name. These have the type 1191:c:expr:`PyObject*`; they are all class objects. For completeness, here are all 1192the variables: 1193 1194.. index:: 1195 single: PyExc_Warning (C var) 1196 single: PyExc_BytesWarning (C var) 1197 single: PyExc_DeprecationWarning (C var) 1198 single: PyExc_FutureWarning (C var) 1199 single: PyExc_ImportWarning (C var) 1200 single: PyExc_PendingDeprecationWarning (C var) 1201 single: PyExc_ResourceWarning (C var) 1202 single: PyExc_RuntimeWarning (C var) 1203 single: PyExc_SyntaxWarning (C var) 1204 single: PyExc_UnicodeWarning (C var) 1205 single: PyExc_UserWarning (C var) 1206 1207+------------------------------------------+---------------------------------+----------+ 1208| C Name | Python Name | Notes | 1209+==========================================+=================================+==========+ 1210| :c:data:`PyExc_Warning` | :exc:`Warning` | [3]_ | 1211+------------------------------------------+---------------------------------+----------+ 1212| :c:data:`PyExc_BytesWarning` | :exc:`BytesWarning` | | 1213+------------------------------------------+---------------------------------+----------+ 1214| :c:data:`PyExc_DeprecationWarning` | :exc:`DeprecationWarning` | | 1215+------------------------------------------+---------------------------------+----------+ 1216| :c:data:`PyExc_FutureWarning` | :exc:`FutureWarning` | | 1217+------------------------------------------+---------------------------------+----------+ 1218| :c:data:`PyExc_ImportWarning` | :exc:`ImportWarning` | | 1219+------------------------------------------+---------------------------------+----------+ 1220| :c:data:`PyExc_PendingDeprecationWarning`| :exc:`PendingDeprecationWarning`| | 1221+------------------------------------------+---------------------------------+----------+ 1222| :c:data:`PyExc_ResourceWarning` | :exc:`ResourceWarning` | | 1223+------------------------------------------+---------------------------------+----------+ 1224| :c:data:`PyExc_RuntimeWarning` | :exc:`RuntimeWarning` | | 1225+------------------------------------------+---------------------------------+----------+ 1226| :c:data:`PyExc_SyntaxWarning` | :exc:`SyntaxWarning` | | 1227+------------------------------------------+---------------------------------+----------+ 1228| :c:data:`PyExc_UnicodeWarning` | :exc:`UnicodeWarning` | | 1229+------------------------------------------+---------------------------------+----------+ 1230| :c:data:`PyExc_UserWarning` | :exc:`UserWarning` | | 1231+------------------------------------------+---------------------------------+----------+ 1232 1233.. versionadded:: 3.2 1234 :c:data:`PyExc_ResourceWarning`. 1235 1236Notes: 1237 1238.. [3] 1239 This is a base class for other standard warning categories. 1240