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