Debian Codegraph @

Doc/c-api/exceptions.rst

raw
1 .. highlight:: c
2
3
4 .. _exceptionhandling:
5
6 ******************
7 Exception Handling
8 ******************
9
10 The functions described in this chapter will let you handle and raise Python
11 exceptions. It is important to understand some of the basics of Python
12 exception handling. It works somewhat like the POSIX :c:data:`errno` variable:
13 there is a global indicator (per thread) of the last error that occurred. Most
14 C API functions don't clear this on success, but will set it to indicate the
15 cause of the error on failure. Most C API functions also return an error
16 indicator, usually ``NULL`` if they are supposed to return a pointer, or ``-1``
17 if they return an integer (exception: the ``PyArg_*`` functions
18 return ``1`` for success and ``0`` for failure).
19
20 Concretely, the error indicator consists of three object pointers: the
21 exception's type, the exception's value, and the traceback object. Any
22 of those pointers can be ``NULL`` if non-set (although some combinations are
23 forbidden, for example you can't have a non-``NULL`` traceback if the exception
24 type is ``NULL``).
25
26 When a function must fail because some function it called failed, it generally
27 doesn't set the error indicator; the function it called already set it. It is
28 responsible for either handling the error and clearing the exception or
29 returning after cleaning up any resources it holds (such as object references or
30 memory allocations); it should *not* continue normally if it is not prepared to
31 handle the error. If returning due to an error, it is important to indicate to
32 the caller that an error has been set. If the error is not handled or carefully
33 propagated, additional calls into the Python/C API may not behave as intended
34 and 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
43 Printing 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
122 Raising exceptions
123 ==================
124
125 These functions help you set the current thread's error indicator.
126 For 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_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset, int end_lineno, int end_col_offset)
313
314 Similar to :c:func:`PyErr_SyntaxLocationObject`, but also sets the
315 *end_lineno* and *end_col_offset* information for the current exception.
316
317 .. versionadded:: 3.10
318
319
320 .. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
321
322 Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
323 decoded from the :term:`filesystem encoding and error handler`.
324
325 .. versionadded:: 3.2
326
327
328 .. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
329
330 Like :c:func:`PyErr_SyntaxLocationEx`, but the *col_offset* parameter is
331 omitted.
332
333
334 .. c:function:: void PyErr_BadInternalCall()
335
336 This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
337 where *message* indicates that an internal operation (e.g. a Python/C API
338 function) was invoked with an illegal argument. It is mostly for internal
339 use.
340
341
342 .. c:function:: PyObject *PyErr_ProgramTextObject(PyObject *filename, int lineno)
343
344 Get the source line in *filename* at line *lineno*. *filename* should be a
345 Python :class:`str` object.
346
347 On success, this function returns a Python string object with the found line.
348 On failure, this function returns ``NULL`` without an exception set.
349
350
351 .. c:function:: PyObject *PyErr_ProgramText(const char *filename, int lineno)
352
353 Similar to :c:func:`PyErr_ProgramTextObject`, but *filename* is a
354 :c:expr:`const char *`, which is decoded with the
355 :term:`filesystem encoding and error handler`, instead of a
356 Python object reference.
357
358
359 Issuing warnings
360 ================
361
362 Use these functions to issue warnings from C code. They mirror similar
363 functions exported by the Python :mod:`warnings` module. They normally
364 print a warning message to *sys.stderr*; however, it is
365 also possible that the user has specified that warnings are to be turned into
366 errors, and in that case they will raise an exception. It is also possible that
367 the functions raise an exception because of a problem with the warning machinery.
368 The return value is ``0`` if no exception is raised, or ``-1`` if an exception
369 is raised. (It is not possible to determine whether a warning message is
370 actually printed, nor what the reason is for the exception; this is
371 intentional.) If an exception is raised, the caller should do its normal
372 exception handling (for example, :c:func:`Py_DECREF` owned references and return
373 an error value).
374
375 .. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
376
377 Issue a warning message. The *category* argument is a warning category (see
378 below) or ``NULL``; the *message* argument is a UTF-8 encoded string. *stack_level* is a
379 positive number giving a number of stack frames; the warning will be issued from
380 the currently executing line of code in that stack frame. A *stack_level* of 1
381 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that,
382 and so forth.
383
384 Warning categories must be subclasses of :c:data:`PyExc_Warning`;
385 :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`;
386 the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard
387 Python warning categories are available as global variables whose names are
388 enumerated at :ref:`standardwarningcategories`.
389
390 For information about warning control, see the documentation for the
391 :mod:`warnings` module and the :option:`-W` option in the command line
392 documentation. There is no C API for warning control.
393
394
395 .. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
396
397 Issue a warning message with explicit control over all warning attributes. This
398 is a straightforward wrapper around the Python function
399 :func:`warnings.warn_explicit`; see there for more information. The *module*
400 and *registry* arguments may be set to ``NULL`` to get the default effect
401 described there.
402
403 .. versionadded:: 3.4
404
405
406 .. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
407
408 Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and
409 *module* are UTF-8 encoded strings, and *filename* is decoded from the
410 :term:`filesystem encoding and error handler`.
411
412
413 .. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
414
415 Function similar to :c:func:`PyErr_WarnEx`, but use
416 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
417 an ASCII-encoded string.
418
419 .. versionadded:: 3.2
420
421
422 .. c:function:: int PyErr_WarnExplicitFormat(PyObject *category, const char *filename, int lineno, const char *module, PyObject *registry, const char *format, ...)
423
424 Similar to :c:func:`PyErr_WarnExplicit`, but uses
425 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
426 an ASCII-encoded string.
427
428 .. versionadded:: 3.2
429
430
431 .. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
432
433 Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
434 :exc:`ResourceWarning` and it passes *source* to :class:`!warnings.WarningMessage`.
435
436 .. versionadded:: 3.6
437
438
439 Querying the error indicator
440 ============================
441
442 .. c:function:: PyObject* PyErr_Occurred()
443
444 Test whether the error indicator is set. If set, return the exception *type*
445 (the first argument to the last call to one of the ``PyErr_Set*``
446 functions or to :c:func:`PyErr_Restore`). If not set, return ``NULL``. You do not
447 own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
448 it.
449
450 The caller must hold the GIL.
451
452 .. note::
453
454 Do not compare the return value to a specific exception; use
455 :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could
456 easily fail since the exception may be an instance instead of a class, in the
457 case of a class exception, or it may be a subclass of the expected exception.)
458
459
460 .. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
461
462 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This
463 should only be called when an exception is actually set; a memory access
464 violation will occur if no exception has been raised.
465
466
467 .. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
468
469 Return true if the *given* exception matches the exception type in *exc*. If
470 *exc* is a class object, this also returns true when *given* is an instance
471 of a subclass. If *exc* is a tuple, all exception types in the tuple (and
472 recursively in subtuples) are searched for a match.
473
474
475 .. c:function:: PyObject *PyErr_GetRaisedException(void)
476
477 Return the exception currently being raised, clearing the error indicator at
478 the same time. Return ``NULL`` if the error indicator is not set.
479
480 This function is used by code that needs to catch exceptions,
481 or code that needs to save and restore the error indicator temporarily.
482
483 For example::
484
485 {
486 PyObject *exc = PyErr_GetRaisedException();
487
488 /* ... code that might produce other errors ... */
489
490 PyErr_SetRaisedException(exc);
491 }
492
493 .. seealso:: :c:func:`PyErr_GetHandledException`,
494 to save the exception currently being handled.
495
496 .. versionadded:: 3.12
497
498
499 .. c:function:: void PyErr_SetRaisedException(PyObject *exc)
500
501 Set *exc* as the exception currently being raised,
502 clearing the existing exception if one is set.
503
504 .. warning::
505
506 This call steals a reference to *exc*, which must be a valid exception.
507
508 .. versionadded:: 3.12
509
510
511 .. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
512
513 .. deprecated:: 3.12
514
515 Use :c:func:`PyErr_GetRaisedException` instead.
516
517 Retrieve the error indicator into three variables whose addresses are passed.
518 If the error indicator is not set, set all three variables to ``NULL``. If it is
519 set, it will be cleared and you own a reference to each object retrieved. The
520 value and traceback object may be ``NULL`` even when the type object is not.
521
522 .. note::
523
524 This function is normally only used by legacy code that needs to catch
525 exceptions or save and restore the error indicator temporarily.
526
527 For example::
528
529 {
530 PyObject *type, *value, *traceback;
531 PyErr_Fetch(&type, &value, &traceback);
532
533 /* ... code that might produce other errors ... */
534
535 PyErr_Restore(type, value, traceback);
536 }
537
538
539 .. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
540
541 .. deprecated:: 3.12
542
543 Use :c:func:`PyErr_SetRaisedException` instead.
544
545 Set the error indicator from the three objects,
546 *type*, *value*, and *traceback*,
547 clearing the existing exception if one is set.
548 If the objects are ``NULL``, the error
549 indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or
550 traceback. The exception type should be a class. Do not pass an invalid
551 exception type or value. (Violating these rules will cause subtle problems
552 later.) This call takes away a reference to each object: you must own a
553 reference to each object before the call and after the call you no longer own
554 these references. (If you don't understand this, don't use this function. I
555 warned you.)
556
557 .. note::
558
559 This function is normally only used by legacy code that needs to
560 save and restore the error indicator temporarily.
561 Use :c:func:`PyErr_Fetch` to save the current error indicator.
562
563
564 .. c:function:: void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
565
566 .. deprecated:: 3.12
567
568 Use :c:func:`PyErr_GetRaisedException` instead,
569 to avoid any possible de-normalization.
570
571 Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
572 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
573 not an instance of the same class. This function can be used to instantiate
574 the class in that case. If the values are already normalized, nothing happens.
575 The delayed normalization is implemented to improve performance.
576
577 .. note::
578
579 This function *does not* implicitly set the
580 :attr:`~BaseException.__traceback__`
581 attribute on the exception value. If setting the traceback
582 appropriately is desired, the following additional snippet is needed::
583
584 if (tb != NULL) {
585 PyException_SetTraceback(val, tb);
586 }
587
588
589 .. c:function:: PyObject* PyErr_GetHandledException(void)
590
591 Retrieve the active exception instance, as would be returned by :func:`sys.exception`.
592 This refers to an exception that was *already caught*, not to an exception that was
593 freshly raised. Returns a new reference to the exception or ``NULL``.
594 Does not modify the interpreter's exception state.
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_SetHandledException` to restore or
601 clear the exception state.
602
603 .. versionadded:: 3.11
604
605 .. c:function:: void PyErr_SetHandledException(PyObject *exc)
606
607 Set the active exception, as known from ``sys.exception()``. This refers
608 to an exception that was *already caught*, not to an exception that was
609 freshly raised.
610 To clear the exception state, pass ``NULL``.
611
612 .. note::
613
614 This function is not normally used by code that wants to handle exceptions.
615 Rather, it can be used when code needs to save and restore the exception
616 state temporarily. Use :c:func:`PyErr_GetHandledException` to get the exception
617 state.
618
619 .. versionadded:: 3.11
620
621 .. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
622
623 Retrieve the old-style representation of the exception info, as known from
624 :func:`sys.exc_info`. This refers to an exception that was *already caught*,
625 not to an exception that was freshly raised. Returns new references for the
626 three objects, any of which may be ``NULL``. Does not modify the exception
627 info state. This function is kept for backwards compatibility. Prefer using
628 :c:func:`PyErr_GetHandledException`.
629
630 .. note::
631
632 This function is not normally used by code that wants to handle exceptions.
633 Rather, it can be used when code needs to save and restore the exception
634 state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the
635 exception state.
636
637 .. versionadded:: 3.3
638
639
640 .. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
641
642 Set the exception info, as known from ``sys.exc_info()``. This refers
643 to an exception that was *already caught*, not to an exception that was
644 freshly raised. This function steals the references of the arguments.
645 To clear the exception state, pass ``NULL`` for all three arguments.
646 This function is kept for backwards compatibility. Prefer using
647 :c:func:`PyErr_SetHandledException`.
648
649 .. note::
650
651 This function is not normally used by code that wants to handle exceptions.
652 Rather, it can be used when code needs to save and restore the exception
653 state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception
654 state.
655
656 .. versionadded:: 3.3
657
658 .. versionchanged:: 3.11
659 The ``type`` and ``traceback`` arguments are no longer used and
660 can be NULL. The interpreter now derives them from the exception
661 instance (the ``value`` argument). The function still steals
662 references of all three arguments.
663
664
665 Signal Handling
666 ===============
667
668
669 .. c:function:: int PyErr_CheckSignals()
670
671 .. index::
672 pair: module; signal
673 single: SIGINT (C macro)
674 single: KeyboardInterrupt (built-in exception)
675
676 This function interacts with Python's signal handling.
677
678 If the function is called from the main thread and under the main Python
679 interpreter, it checks whether a signal has been sent to the processes
680 and if so, invokes the corresponding signal handler. If the :mod:`signal`
681 module is supported, this can invoke a signal handler written in Python.
682
683 The function attempts to handle all pending signals, and then returns ``0``.
684 However, if a Python signal handler raises an exception, the error
685 indicator is set and the function returns ``-1`` immediately (such that
686 other pending signals may not have been handled yet: they will be on the
687 next :c:func:`PyErr_CheckSignals()` invocation).
688
689 If the function is called from a non-main thread, or under a non-main
690 Python interpreter, it does nothing and returns ``0``.
691
692 This function can be called by long-running C code that wants to
693 be interruptible by user requests (such as by pressing Ctrl-C).
694
695 .. note::
696 The default Python signal handler for :c:macro:`!SIGINT` raises the
697 :exc:`KeyboardInterrupt` exception.
698
699
700 .. c:function:: void PyErr_SetInterrupt()
701
702 .. index::
703 pair: module; signal
704 single: SIGINT (C macro)
705 single: KeyboardInterrupt (built-in exception)
706
707 Simulate the effect of a :c:macro:`!SIGINT` signal arriving.
708 This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``.
709
710 .. note::
711 This function is async-signal-safe. It can be called without
712 the :term:`GIL` and from a C signal handler.
713
714
715 .. c:function:: int PyErr_SetInterruptEx(int signum)
716
717 .. index::
718 pair: module; signal
719 single: KeyboardInterrupt (built-in exception)
720
721 Simulate the effect of a signal arriving. The next time
722 :c:func:`PyErr_CheckSignals` is called, the Python signal handler for
723 the given signal number will be called.
724
725 This function can be called by C code that sets up its own signal handling
726 and wants Python signal handlers to be invoked as expected when an
727 interruption is requested (for example when the user presses Ctrl-C
728 to interrupt an operation).
729
730 If the given signal isn't handled by Python (it was set to
731 :py:const:`signal.SIG_DFL` or :py:const:`signal.SIG_IGN`), it will be ignored.
732
733 If *signum* is outside of the allowed range of signal numbers, ``-1``
734 is returned. Otherwise, ``0`` is returned. The error indicator is
735 never changed by this function.
736
737 .. note::
738 This function is async-signal-safe. It can be called without
739 the :term:`GIL` and from a C signal handler.
740
741 .. versionadded:: 3.10
742
743
744 .. c:function:: int PySignal_SetWakeupFd(int fd)
745
746 This utility function specifies a file descriptor to which the signal number
747 is written as a single byte whenever a signal is received. *fd* must be
748 non-blocking. It returns the previous such file descriptor.
749
750 The value ``-1`` disables the feature; this is the initial state.
751 This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
752 error checking. *fd* should be a valid file descriptor. The function should
753 only be called from the main thread.
754
755 .. versionchanged:: 3.5
756 On Windows, the function now also supports socket handles.
757
758
759 Exception Classes
760 =================
761
762 .. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
763
764 This utility function creates and returns a new exception class. The *name*
765 argument must be the name of the new exception, a C string of the form
766 ``module.classname``. The *base* and *dict* arguments are normally ``NULL``.
767 This creates a class object derived from :exc:`Exception` (accessible in C as
768 :c:data:`PyExc_Exception`).
769
770 The :attr:`~type.__module__` attribute of the new class is set to the first part (up
771 to the last dot) of the *name* argument, and the class name is set to the last
772 part (after the last dot). The *base* argument can be used to specify alternate
773 base classes; it can either be only one class or a tuple of classes. The *dict*
774 argument can be used to specify a dictionary of class variables and methods.
775
776
777 .. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
778
779 Same as :c:func:`PyErr_NewException`, except that the new exception class can
780 easily be given a docstring: If *doc* is non-``NULL``, it will be used as the
781 docstring for the exception class.
782
783 .. versionadded:: 3.2
784
785
786 .. c:function:: int PyExceptionClass_Check(PyObject *ob)
787
788 Return non-zero if *ob* is an exception class, zero otherwise. This function always succeeds.
789
790
791 .. c:function:: const char *PyExceptionClass_Name(PyObject *ob)
792
793 Return :c:member:`~PyTypeObject.tp_name` of the exception class *ob*.
794
795
796 Exception Objects
797 =================
798
799 .. c:function:: int PyExceptionInstance_Check(PyObject *op)
800
801 Return true if *op* is an instance of :class:`BaseException`, false
802 otherwise. This function always succeeds.
803
804
805 .. c:macro:: PyExceptionInstance_Class(op)
806
807 Equivalent to :c:func:`Py_TYPE(op) <Py_TYPE>`.
808
809
810 .. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
811
812 Return the traceback associated with the exception as a new reference, as
813 accessible from Python through the :attr:`~BaseException.__traceback__`
814 attribute. If there is no
815 traceback associated, this returns ``NULL``.
816
817
818 .. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
819
820 Set the traceback associated with the exception to *tb*. Use ``Py_None`` to
821 clear it.
822
823
824 .. c:function:: PyObject* PyException_GetContext(PyObject *ex)
825
826 Return the context (another exception instance during whose handling *ex* was
827 raised) associated with the exception as a new reference, as accessible from
828 Python through the :attr:`~BaseException.__context__` attribute.
829 If there is no context associated, this returns ``NULL``.
830
831
832 .. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
833
834 Set the context associated with the exception to *ctx*. Use ``NULL`` to clear
835 it. There is no type check to make sure that *ctx* is an exception instance.
836 This steals a reference to *ctx*.
837
838
839 .. c:function:: PyObject* PyException_GetCause(PyObject *ex)
840
841 Return the cause (either an exception instance, or ``None``,
842 set by ``raise ... from ...``) associated with the exception as a new
843 reference, as accessible from Python through the
844 :attr:`~BaseException.__cause__` attribute.
845
846
847 .. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
848
849 Set the cause associated with the exception to *cause*. Use ``NULL`` to clear
850 it. There is no type check to make sure that *cause* is either an exception
851 instance or ``None``. This steals a reference to *cause*.
852
853 The :attr:`~BaseException.__suppress_context__` attribute is implicitly set
854 to ``True`` by this function.
855
856
857 .. c:function:: PyObject* PyException_GetArgs(PyObject *ex)
858
859 Return :attr:`~BaseException.args` of exception *ex*.
860
861
862 .. c:function:: void PyException_SetArgs(PyObject *ex, PyObject *args)
863
864 Set :attr:`~BaseException.args` of exception *ex* to *args*.
865
866 .. c:function:: PyObject* PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)
867
868 Implement part of the interpreter's implementation of :keyword:`!except*`.
869 *orig* is the original exception that was caught, and *excs* is the list of
870 the exceptions that need to be raised. This list contains the unhandled
871 part of *orig*, if any, as well as the exceptions that were raised from the
872 :keyword:`!except*` clauses (so they have a different traceback from *orig*) and
873 those that were reraised (and have the same traceback as *orig*).
874 Return the :exc:`ExceptionGroup` that needs to be reraised in the end, or
875 ``None`` if there is nothing to reraise.
876
877 .. versionadded:: 3.12
878
879 .. _unicodeexceptions:
880
881 Unicode Exception Objects
882 =========================
883
884 The following functions are used to create and modify Unicode exceptions from C.
885
886 .. 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)
887
888 Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
889 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
890 UTF-8 encoded strings.
891
892 .. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
893 PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
894
895 Return the *encoding* attribute of the given exception object.
896
897 .. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
898 PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
899 PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
900
901 Return the *object* attribute of the given exception object.
902
903 .. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
904 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
905 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
906
907 Get the *start* attribute of the given exception object and place it into
908 *\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` on
909 failure.
910
911 .. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
912 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
913 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
914
915 Set the *start* attribute of the given exception object to *start*. Return
916 ``0`` on success, ``-1`` on failure.
917
918 .. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
919 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
920 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
921
922 Get the *end* attribute of the given exception object and place it into
923 *\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on
924 failure.
925
926 .. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
927 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
928 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
929
930 Set the *end* attribute of the given exception object to *end*. Return ``0``
931 on success, ``-1`` on failure.
932
933 .. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
934 PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
935 PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
936
937 Return the *reason* attribute of the given exception object.
938
939 .. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
940 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
941 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
942
943 Set the *reason* attribute of the given exception object to *reason*. Return
944 ``0`` on success, ``-1`` on failure.
945
946
947 .. _recursion:
948
949 Recursion Control
950 =================
951
952 These two functions provide a way to perform safe recursive calls at the C
953 level, both in the core and in extension modules. They are needed if the
954 recursive code does not necessarily invoke Python code (which tracks its
955 recursion depth automatically).
956 They are also not needed for *tp_call* implementations
957 because the :ref:`call protocol <call>` takes care of recursion handling.
958
959 .. c:function:: int Py_EnterRecursiveCall(const char *where)
960
961 Marks a point where a recursive C-level call is about to be performed.
962
963 If :c:macro:`!USE_STACKCHECK` is defined, this function checks if the OS
964 stack overflowed using :c:func:`PyOS_CheckStack`. If this is the case, it
965 sets a :exc:`MemoryError` and returns a nonzero value.
966
967 The function then checks if the recursion limit is reached. If this is the
968 case, a :exc:`RecursionError` is set and a nonzero value is returned.
969 Otherwise, zero is returned.
970
971 *where* should be a UTF-8 encoded string such as ``" in instance check"`` to
972 be concatenated to the :exc:`RecursionError` message caused by the recursion
973 depth limit.
974
975 .. versionchanged:: 3.9
976 This function is now also available in the :ref:`limited API <limited-c-api>`.
977
978 .. c:function:: void Py_LeaveRecursiveCall(void)
979
980 Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each
981 *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
982
983 .. versionchanged:: 3.9
984 This function is now also available in the :ref:`limited API <limited-c-api>`.
985
986 Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
987 special recursion handling. In addition to protecting the stack,
988 :c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The
989 following two functions facilitate this functionality. Effectively,
990 these are the C equivalent to :func:`reprlib.recursive_repr`.
991
992 .. c:function:: int Py_ReprEnter(PyObject *object)
993
994 Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
995 detect cycles.
996
997 If the object has already been processed, the function returns a
998 positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation
999 should return a string object indicating a cycle. As examples,
1000 :class:`dict` objects return ``{...}`` and :class:`list` objects
1001 return ``[...]``.
1002
1003 The function will return a negative integer if the recursion limit
1004 is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
1005 typically return ``NULL``.
1006
1007 Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
1008 implementation can continue normally.
1009
1010 .. c:function:: void Py_ReprLeave(PyObject *object)
1011
1012 Ends a :c:func:`Py_ReprEnter`. Must be called once for each
1013 invocation of :c:func:`Py_ReprEnter` that returns zero.
1014
1015 .. c:function:: int Py_GetRecursionLimit(void)
1016
1017 Get the recursion limit for the current interpreter. It can be set with
1018 :c:func:`Py_SetRecursionLimit`. The recursion limit prevents the
1019 Python interpreter stack from growing infinitely.
1020
1021 This function cannot fail, and the caller must hold the
1022 :term:`GIL`.
1023
1024 .. seealso::
1025 :py:func:`sys.getrecursionlimit`
1026
1027 .. c:function:: void Py_SetRecursionLimit(int new_limit)
1028
1029 Set the recursion limit for the current interpreter.
1030
1031 This function cannot fail, and the caller must hold the
1032 :term:`GIL`.
1033
1034 .. seealso::
1035 :py:func:`sys.setrecursionlimit`
1036
1037 .. _standardexceptions:
1038
1039 Exception and warning types
1040 ===========================
1041
1042 All standard Python exceptions and warning categories are available as global
1043 variables whose names are ``PyExc_`` followed by the Python exception name.
1044 These have the type :c:expr:`PyObject*`; they are all class objects.
1045
1046 For completeness, here are all the variables:
1047
1048 Exception types
1049 ---------------
1050
1051 .. list-table::
1052 :align: left
1053 :widths: auto
1054 :header-rows: 1
1055
1056 * * C name
1057 * Python name
1058 * * .. c:var:: PyObject *PyExc_BaseException
1059 * :exc:`BaseException`
1060 * * .. c:var:: PyObject *PyExc_BaseExceptionGroup
1061 * :exc:`BaseExceptionGroup`
1062 * * .. c:var:: PyObject *PyExc_Exception
1063 * :exc:`Exception`
1064 * * .. c:var:: PyObject *PyExc_ArithmeticError
1065 * :exc:`ArithmeticError`
1066 * * .. c:var:: PyObject *PyExc_AssertionError
1067 * :exc:`AssertionError`
1068 * * .. c:var:: PyObject *PyExc_AttributeError
1069 * :exc:`AttributeError`
1070 * * .. c:var:: PyObject *PyExc_BlockingIOError
1071 * :exc:`BlockingIOError`
1072 * * .. c:var:: PyObject *PyExc_BrokenPipeError
1073 * :exc:`BrokenPipeError`
1074 * * .. c:var:: PyObject *PyExc_BufferError
1075 * :exc:`BufferError`
1076 * * .. c:var:: PyObject *PyExc_ChildProcessError
1077 * :exc:`ChildProcessError`
1078 * * .. c:var:: PyObject *PyExc_ConnectionAbortedError
1079 * :exc:`ConnectionAbortedError`
1080 * * .. c:var:: PyObject *PyExc_ConnectionError
1081 * :exc:`ConnectionError`
1082 * * .. c:var:: PyObject *PyExc_ConnectionRefusedError
1083 * :exc:`ConnectionRefusedError`
1084 * * .. c:var:: PyObject *PyExc_ConnectionResetError
1085 * :exc:`ConnectionResetError`
1086 * * .. c:var:: PyObject *PyExc_EOFError
1087 * :exc:`EOFError`
1088 * * .. c:var:: PyObject *PyExc_FileExistsError
1089 * :exc:`FileExistsError`
1090 * * .. c:var:: PyObject *PyExc_FileNotFoundError
1091 * :exc:`FileNotFoundError`
1092 * * .. c:var:: PyObject *PyExc_FloatingPointError
1093 * :exc:`FloatingPointError`
1094 * * .. c:var:: PyObject *PyExc_GeneratorExit
1095 * :exc:`GeneratorExit`
1096 * * .. c:var:: PyObject *PyExc_ImportError
1097 * :exc:`ImportError`
1098 * * .. c:var:: PyObject *PyExc_IndentationError
1099 * :exc:`IndentationError`
1100 * * .. c:var:: PyObject *PyExc_IndexError
1101 * :exc:`IndexError`
1102 * * .. c:var:: PyObject *PyExc_InterruptedError
1103 * :exc:`InterruptedError`
1104 * * .. c:var:: PyObject *PyExc_IsADirectoryError
1105 * :exc:`IsADirectoryError`
1106 * * .. c:var:: PyObject *PyExc_KeyError
1107 * :exc:`KeyError`
1108 * * .. c:var:: PyObject *PyExc_KeyboardInterrupt
1109 * :exc:`KeyboardInterrupt`
1110 * * .. c:var:: PyObject *PyExc_LookupError
1111 * :exc:`LookupError`
1112 * * .. c:var:: PyObject *PyExc_MemoryError
1113 * :exc:`MemoryError`
1114 * * .. c:var:: PyObject *PyExc_ModuleNotFoundError
1115 * :exc:`ModuleNotFoundError`
1116 * * .. c:var:: PyObject *PyExc_NameError
1117 * :exc:`NameError`
1118 * * .. c:var:: PyObject *PyExc_NotADirectoryError
1119 * :exc:`NotADirectoryError`
1120 * * .. c:var:: PyObject *PyExc_NotImplementedError
1121 * :exc:`NotImplementedError`
1122 * * .. c:var:: PyObject *PyExc_OSError
1123 * :exc:`OSError`
1124 * * .. c:var:: PyObject *PyExc_OverflowError
1125 * :exc:`OverflowError`
1126 * * .. c:var:: PyObject *PyExc_PermissionError
1127 * :exc:`PermissionError`
1128 * * .. c:var:: PyObject *PyExc_ProcessLookupError
1129 * :exc:`ProcessLookupError`
1130 * * .. c:var:: PyObject *PyExc_PythonFinalizationError
1131 * :exc:`PythonFinalizationError`
1132 * * .. c:var:: PyObject *PyExc_RecursionError
1133 * :exc:`RecursionError`
1134 * * .. c:var:: PyObject *PyExc_ReferenceError
1135 * :exc:`ReferenceError`
1136 * * .. c:var:: PyObject *PyExc_RuntimeError
1137 * :exc:`RuntimeError`
1138 * * .. c:var:: PyObject *PyExc_StopAsyncIteration
1139 * :exc:`StopAsyncIteration`
1140 * * .. c:var:: PyObject *PyExc_StopIteration
1141 * :exc:`StopIteration`
1142 * * .. c:var:: PyObject *PyExc_SyntaxError
1143 * :exc:`SyntaxError`
1144 * * .. c:var:: PyObject *PyExc_SystemError
1145 * :exc:`SystemError`
1146 * * .. c:var:: PyObject *PyExc_SystemExit
1147 * :exc:`SystemExit`
1148 * * .. c:var:: PyObject *PyExc_TabError
1149 * :exc:`TabError`
1150 * * .. c:var:: PyObject *PyExc_TimeoutError
1151 * :exc:`TimeoutError`
1152 * * .. c:var:: PyObject *PyExc_TypeError
1153 * :exc:`TypeError`
1154 * * .. c:var:: PyObject *PyExc_UnboundLocalError
1155 * :exc:`UnboundLocalError`
1156 * * .. c:var:: PyObject *PyExc_UnicodeDecodeError
1157 * :exc:`UnicodeDecodeError`
1158 * * .. c:var:: PyObject *PyExc_UnicodeEncodeError
1159 * :exc:`UnicodeEncodeError`
1160 * * .. c:var:: PyObject *PyExc_UnicodeError
1161 * :exc:`UnicodeError`
1162 * * .. c:var:: PyObject *PyExc_UnicodeTranslateError
1163 * :exc:`UnicodeTranslateError`
1164 * * .. c:var:: PyObject *PyExc_ValueError
1165 * :exc:`ValueError`
1166 * * .. c:var:: PyObject *PyExc_ZeroDivisionError
1167 * :exc:`ZeroDivisionError`
1168
1169 .. versionadded:: 3.3
1170 :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
1171 :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
1172 :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
1173 :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
1174 :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
1175 :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
1176 :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
1177 and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
1178
1179 .. versionadded:: 3.5
1180 :c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`.
1181
1182 .. versionadded:: 3.6
1183 :c:data:`PyExc_ModuleNotFoundError`.
1184
1185 .. versionadded:: 3.11
1186 :c:data:`PyExc_BaseExceptionGroup`.
1187
1188
1189 OSError aliases
1190 ---------------
1191
1192 The following are a compatibility aliases to :c:data:`PyExc_OSError`.
1193
1194 .. versionchanged:: 3.3
1195 These aliases used to be separate exception types.
1196
1197 .. list-table::
1198 :align: left
1199 :widths: auto
1200 :header-rows: 1
1201
1202 * * C name
1203 * Python name
1204 * Notes
1205 * * .. c:var:: PyObject *PyExc_EnvironmentError
1206 * :exc:`OSError`
1207 *
1208 * * .. c:var:: PyObject *PyExc_IOError
1209 * :exc:`OSError`
1210 *
1211 * * .. c:var:: PyObject *PyExc_WindowsError
1212 * :exc:`OSError`
1213 * [win]_
1214
1215 Notes:
1216
1217 .. [win]
1218 :c:var:`!PyExc_WindowsError` is only defined on Windows; protect code that
1219 uses this by testing that the preprocessor macro ``MS_WINDOWS`` is defined.
1220
1221
1222 .. _standardwarningcategories:
1223
1224 Warning types
1225 -------------
1226
1227 .. list-table::
1228 :align: left
1229 :widths: auto
1230 :header-rows: 1
1231
1232 * * C name
1233 * Python name
1234 * * .. c:var:: PyObject *PyExc_Warning
1235 * :exc:`Warning`
1236 * * .. c:var:: PyObject *PyExc_BytesWarning
1237 * :exc:`BytesWarning`
1238 * * .. c:var:: PyObject *PyExc_DeprecationWarning
1239 * :exc:`DeprecationWarning`
1240 * * .. c:var:: PyObject *PyExc_EncodingWarning
1241 * :exc:`EncodingWarning`
1242 * * .. c:var:: PyObject *PyExc_FutureWarning
1243 * :exc:`FutureWarning`
1244 * * .. c:var:: PyObject *PyExc_ImportWarning
1245 * :exc:`ImportWarning`
1246 * * .. c:var:: PyObject *PyExc_PendingDeprecationWarning
1247 * :exc:`PendingDeprecationWarning`
1248 * * .. c:var:: PyObject *PyExc_ResourceWarning
1249 * :exc:`ResourceWarning`
1250 * * .. c:var:: PyObject *PyExc_RuntimeWarning
1251 * :exc:`RuntimeWarning`
1252 * * .. c:var:: PyObject *PyExc_SyntaxWarning
1253 * :exc:`SyntaxWarning`
1254 * * .. c:var:: PyObject *PyExc_UnicodeWarning
1255 * :exc:`UnicodeWarning`
1256 * * .. c:var:: PyObject *PyExc_UserWarning
1257 * :exc:`UserWarning`
1258
1259 .. versionadded:: 3.2
1260 :c:data:`PyExc_ResourceWarning`.
1261
1262 .. versionadded:: 3.10
1263 :c:data:`PyExc_EncodingWarning`.
1264
1265
1266 Tracebacks
1267 ==========
1268
1269 .. c:var:: PyTypeObject PyTraceBack_Type
1270
1271 Type object for traceback objects. This is available as
1272 :class:`types.TracebackType` in the Python layer.
1273
1274
1275 .. c:function:: int PyTraceBack_Check(PyObject *op)
1276
1277 Return true if *op* is a traceback object, false otherwise. This function
1278 does not account for subtypes.
1279
1280
1281 .. c:function:: int PyTraceBack_Here(PyFrameObject *f)
1282
1283 Replace the :attr:`~BaseException.__traceback__` attribute on the current
1284 exception with a new traceback prepending *f* to the existing chain.
1285
1286 Calling this function without an exception set is undefined behavior.
1287
1288 This function returns ``0`` on success, and returns ``-1`` with an
1289 exception set on failure.
1290
1291
1292 .. c:function:: int PyTraceBack_Print(PyObject *tb, PyObject *f)
1293
1294 Write the traceback *tb* into the file *f*.
1295
1296 This function returns ``0`` on success, and returns ``-1`` with an
1297 exception set on failure.