blob: 158672d86b325dd7fbdd69401c274255ab3d6d3e [file] [log] [blame]
Stéphane Wirtelcbb64842019-05-17 11:55:34 +02001.. highlight:: c
Georg Brandl116aa622007-08-15 14:28:22 +00002
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
Antoine Pitrou550ff722014-09-30 21:56:10 +020012exception handling. It works somewhat like the POSIX :c:data:`errno` variable:
Georg Brandl116aa622007-08-15 14:28:22 +000013there is a global indicator (per thread) of the last error that occurred. Most
Antoine Pitrou550ff722014-09-30 21:56:10 +020014C 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
Serhiy Storchaka25fc0882019-10-30 12:03:20 +020016indicator, usually ``NULL`` if they are supposed to return a pointer, or ``-1``
Antoine Pitrou550ff722014-09-30 21:56:10 +020017if they return an integer (exception: the :c:func:`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
Serhiy Storchakae835b312019-10-30 21:37:16 +020022of 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``).
Georg Brandl116aa622007-08-15 14:28:22 +000025
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
Antoine Pitrou550ff722014-09-30 21:56:10 +020036.. 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).
Georg Brandl116aa622007-08-15 14:28:22 +000041
Antoine Pitrou550ff722014-09-30 21:56:10 +020042
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.
Georg Brandl116aa622007-08-15 14:28:22 +000051
52
Georg Brandl60203b42010-10-06 10:11:56 +000053.. c:function:: void PyErr_PrintEx(int set_sys_last_vars)
Georg Brandl116aa622007-08-15 14:28:22 +000054
55 Print a standard traceback to ``sys.stderr`` and clear the error indicator.
Daniel Hahlercec01842019-05-06 17:39:06 +020056 **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
Gregory P. Smith41737722019-02-27 15:27:32 -080058 the ``SystemExit`` instance.
59
60 Call this function **only** when the error indicator is set. Otherwise it
61 will cause a fatal error!
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandl115fb352009-02-05 10:56:37 +000063 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
Georg Brandl60203b42010-10-06 10:11:56 +000068.. c:function:: void PyErr_Print()
Georg Brandl115fb352009-02-05 10:56:37 +000069
70 Alias for ``PyErr_PrintEx(1)``.
71
Georg Brandl116aa622007-08-15 14:28:22 +000072
Antoine Pitrou550ff722014-09-30 21:56:10 +020073.. c:function:: void PyErr_WriteUnraisable(PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +000074
Victor Stinneref9d9b62019-05-22 11:28:22 +020075 Call :func:`sys.unraisablehook` using the current exception and *obj*
76 argument.
77
Antoine Pitrou550ff722014-09-30 21:56:10 +020078 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.
Georg Brandl116aa622007-08-15 14:28:22 +000082
Antoine Pitrou550ff722014-09-30 21:56:10 +020083 The function is called with a single argument *obj* that identifies the context
Martin Panter3263f682016-02-28 03:16:11 +000084 in which the unraisable exception occurred. If possible,
85 the repr of *obj* will be printed in the warning message.
Georg Brandl116aa622007-08-15 14:28:22 +000086
Victor Stinneref9d9b62019-05-22 11:28:22 +020087 An exception must be set when calling this function.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089
Antoine Pitrou550ff722014-09-30 21:56:10 +020090Raising exceptions
91==================
Georg Brandl116aa622007-08-15 14:28:22 +000092
Antoine Pitrou550ff722014-09-30 21:56:10 +020093These functions help you set the current thread's error indicator.
94For convenience, some of these functions will always return a
Serhiy Storchakae835b312019-10-30 21:37:16 +020095``NULL`` pointer for use in a ``return`` statement.
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020096
97
Georg Brandl60203b42010-10-06 10:11:56 +000098.. c:function:: void PyErr_SetString(PyObject *type, const char *message)
Georg Brandl116aa622007-08-15 14:28:22 +000099
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,
Georg Brandl60203b42010-10-06 10:11:56 +0000102 e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count.
Victor Stinner257d38f2010-10-09 10:12:11 +0000103 The second argument is an error message; it is decoded from ``'utf-8``'.
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105
Georg Brandl60203b42010-10-06 10:11:56 +0000106.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Georg Brandl60203b42010-10-06 10:11:56 +0000108 This function is similar to :c:func:`PyErr_SetString` but lets you specify an
Georg Brandl116aa622007-08-15 14:28:22 +0000109 arbitrary Python object for the "value" of the exception.
110
111
Georg Brandl60203b42010-10-06 10:11:56 +0000112.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200114 This function sets the error indicator and returns ``NULL``. *exception*
Antoine Pitroua66e0292010-11-27 20:40:43 +0000115 should be a Python exception class. The *format* and subsequent
116 parameters help format the error message; they have the same meaning and
Victor Stinnerb1dbd102010-12-28 11:02:46 +0000117 values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
Victor Stinner555a24f2010-12-27 01:49:26 +0000118 string.
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000119
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Antoine Pitrou0676a402014-09-30 21:16:27 +0200121.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
122
Georg Brandl93a56cd2014-10-30 22:25:41 +0100123 Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather
Antoine Pitrou0676a402014-09-30 21:16:27 +0200124 than a variable number of arguments.
125
126 .. versionadded:: 3.5
127
128
Georg Brandl60203b42010-10-06 10:11:56 +0000129.. c:function:: void PyErr_SetNone(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
132
133
Georg Brandl60203b42010-10-06 10:11:56 +0000134.. c:function:: int PyErr_BadArgument()
Georg Brandl116aa622007-08-15 14:28:22 +0000135
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
Georg Brandl60203b42010-10-06 10:11:56 +0000141.. c:function:: PyObject* PyErr_NoMemory()
Georg Brandl116aa622007-08-15 14:28:22 +0000142
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200143 This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns ``NULL``
Georg Brandl116aa622007-08-15 14:28:22 +0000144 so an object allocation function can write ``return PyErr_NoMemory();`` when it
145 runs out of memory.
146
147
Georg Brandl60203b42010-10-06 10:11:56 +0000148.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150 .. index:: single: strerror()
151
152 This is a convenience function to raise an exception when a C library function
Georg Brandl60203b42010-10-06 10:11:56 +0000153 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`),
Georg Brandl116aa622007-08-15 14:28:22 +0000156 and then calls ``PyErr_SetObject(type, object)``. On Unix, when the
Georg Brandl60203b42010-10-06 10:11:56 +0000157 :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,
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200159 leaves it set to that. The function always returns ``NULL``, so a wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000160 function around a system call can write ``return PyErr_SetFromErrno(type);``
161 when the system call returns an error.
162
163
Georg Brandl991fc572013-04-14 11:12:16 +0200164.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Georg Brandl116aa622007-08-15 14:28:22 +0000165
Georg Brandl60203b42010-10-06 10:11:56 +0000166 Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200167 *filenameObject* is not ``NULL``, it is passed to the constructor of *type* as
Andrew Svetlov08af0002014-04-01 01:13:30 +0300168 a third parameter. In the case of :exc:`OSError` exception,
169 this is used to define the :attr:`filename` attribute of the
Georg Brandl991fc572013-04-14 11:12:16 +0200170 exception instance.
171
172
Larry Hastingsb0827312014-02-09 22:05:19 -0800173.. 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
Georg Brandldf48b972014-03-24 09:06:18 +0100179 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800180
181
Georg Brandl991fc572013-04-14 11:12:16 +0200182.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
183
184 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename
Victor Stinner4b9aad42020-11-02 16:49:54 +0100185 is given as a C string. *filename* is decoded from the :term:`filesystem
186 encoding and error handler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188
Georg Brandl60203b42010-10-06 10:11:56 +0000189.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191 This is a convenience function to raise :exc:`WindowsError`. If called with
Georg Brandl60203b42010-10-06 10:11:56 +0000192 *ierr* of :c:data:`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`,
Georg Brandl116aa622007-08-15 14:28:22 +0000195 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
Georg Brandl60203b42010-10-06 10:11:56 +0000197 :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200198 object)``. This function always returns ``NULL``.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400199
200 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202
Georg Brandl60203b42010-10-06 10:11:56 +0000203.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Georg Brandl60203b42010-10-06 10:11:56 +0000205 Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400206 specifying the exception type to be raised.
207
208 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Georg Brandl60203b42010-10-06 10:11:56 +0000211.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Georg Brandl991fc572013-04-14 11:12:16 +0200213 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
214 filename is given as a C string. *filename* is decoded from the filesystem
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400215 encoding (:func:`os.fsdecode`).
216
217 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219
Georg Brandl991fc572013-04-14 11:12:16 +0200220.. 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.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400224
225 .. availability:: Windows.
Georg Brandl991fc572013-04-14 11:12:16 +0200226
227
Larry Hastingsb0827312014-02-09 22:05:19 -0800228.. 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.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400232
233 .. availability:: Windows.
Larry Hastingsb0827312014-02-09 22:05:19 -0800234
Georg Brandldf48b972014-03-24 09:06:18 +0100235 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800236
237
Georg Brandl991fc572013-04-14 11:12:16 +0200238.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Georg Brandl60203b42010-10-06 10:11:56 +0000240 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400241 parameter specifying the exception type to be raised.
242
243 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Georg Brandlf4095832012-04-24 19:16:24 +0200245
Brian Curtin09b86d12012-04-17 16:57:09 -0500246.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brian Curtinbd439742012-04-16 15:14:36 -0500247
248 This is a convenience function to raise :exc:`ImportError`. *msg* will be
Brian Curtin09b86d12012-04-17 16:57:09 -0500249 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.
Brian Curtinbd439742012-04-16 15:14:36 -0500252
Brian Curtinbded8942012-04-16 18:14:09 -0500253 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000254
Georg Brandlf4095832012-04-24 19:16:24 +0200255
Victor Stinner14e461d2013-08-26 22:28:21 +0200256.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000257
258 Set file, line, and offset information for the current exception. If the
259 current exception is not a :exc:`SyntaxError`, then it sets additional
260 attributes, which make the exception printing subsystem think the exception
Victor Stinner14e461d2013-08-26 22:28:21 +0200261 is a :exc:`SyntaxError`.
Benjamin Peterson2c539712010-09-20 22:42:10 +0000262
Georg Brandldf48b972014-03-24 09:06:18 +0100263 .. versionadded:: 3.4
Victor Stinner14e461d2013-08-26 22:28:21 +0200264
265
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300266.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Victor Stinner14e461d2013-08-26 22:28:21 +0200267
268 Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
Victor Stinner4b9aad42020-11-02 16:49:54 +0100269 decoded from the :term:`filesystem encoding and error handler`.
Victor Stinner14e461d2013-08-26 22:28:21 +0200270
Georg Brandldf48b972014-03-24 09:06:18 +0100271 .. versionadded:: 3.2
Benjamin Petersonb5d23b42010-09-21 21:29:26 +0000272
Benjamin Peterson2c539712010-09-20 22:42:10 +0000273
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300274.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000275
Victor Stinner14e461d2013-08-26 22:28:21 +0200276 Like :c:func:`PyErr_SyntaxLocationEx`, but the col_offset parameter is
Benjamin Peterson2c539712010-09-20 22:42:10 +0000277 omitted.
278
279
Georg Brandl60203b42010-10-06 10:11:56 +0000280.. c:function:: void PyErr_BadInternalCall()
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000282 This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
283 where *message* indicates that an internal operation (e.g. a Python/C API
284 function) was invoked with an illegal argument. It is mostly for internal
285 use.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
Antoine Pitrou550ff722014-09-30 21:56:10 +0200288Issuing warnings
289================
290
291Use these functions to issue warnings from C code. They mirror similar
292functions exported by the Python :mod:`warnings` module. They normally
293print a warning message to *sys.stderr*; however, it is
294also possible that the user has specified that warnings are to be turned into
295errors, and in that case they will raise an exception. It is also possible that
296the functions raise an exception because of a problem with the warning machinery.
297The return value is ``0`` if no exception is raised, or ``-1`` if an exception
298is raised. (It is not possible to determine whether a warning message is
299actually printed, nor what the reason is for the exception; this is
300intentional.) If an exception is raised, the caller should do its normal
301exception handling (for example, :c:func:`Py_DECREF` owned references and return
302an error value).
303
Georg Brandl97435162014-10-06 12:58:00 +0200304.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306 Issue a warning message. The *category* argument is a warning category (see
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200307 below) or ``NULL``; the *message* argument is a UTF-8 encoded string. *stack_level* is a
Georg Brandl116aa622007-08-15 14:28:22 +0000308 positive number giving a number of stack frames; the warning will be issued from
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000309 the currently executing line of code in that stack frame. A *stack_level* of 1
Georg Brandl60203b42010-10-06 10:11:56 +0000310 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that,
Georg Brandl116aa622007-08-15 14:28:22 +0000311 and so forth.
312
cocoatomoeaeda642017-04-15 11:06:02 +0900313 Warning categories must be subclasses of :c:data:`PyExc_Warning`;
314 :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`;
315 the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard
316 Python warning categories are available as global variables whose names are
delirious-lettuce3378b202017-05-19 14:37:57 -0600317 enumerated at :ref:`standardwarningcategories`.
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319 For information about warning control, see the documentation for the
320 :mod:`warnings` module and the :option:`-W` option in the command line
321 documentation. There is no C API for warning control.
322
Hai Shiaeecf382019-07-02 20:56:07 -0500323.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)
Eric Snow46f97b82016-09-07 16:56:15 -0700324
325 Much like :c:func:`PyErr_SetImportError` but this function allows for
326 specifying a subclass of :exc:`ImportError` to raise.
327
Yury Selivanov3479b5f2016-11-10 13:25:26 -0500328 .. versionadded:: 3.6
Eric Snow46f97b82016-09-07 16:56:15 -0700329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
Victor Stinner14e461d2013-08-26 22:28:21 +0200331.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333 Issue a warning message with explicit control over all warning attributes. This
334 is a straightforward wrapper around the Python function
335 :func:`warnings.warn_explicit`, see there for more information. The *module*
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200336 and *registry* arguments may be set to ``NULL`` to get the default effect
Victor Stinner14e461d2013-08-26 22:28:21 +0200337 described there.
338
339 .. versionadded:: 3.4
340
341
342.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
343
344 Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and
345 *module* are UTF-8 encoded strings, and *filename* is decoded from the
Victor Stinner4b9aad42020-11-02 16:49:54 +0100346 :term:`filesystem encoding and error handler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348
Georg Brandl60203b42010-10-06 10:11:56 +0000349.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000350
Georg Brandl60203b42010-10-06 10:11:56 +0000351 Function similar to :c:func:`PyErr_WarnEx`, but use
Victor Stinner555a24f2010-12-27 01:49:26 +0000352 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
353 an ASCII-encoded string.
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000354
355 .. versionadded:: 3.2
356
Georg Brandlf4095832012-04-24 19:16:24 +0200357
Victor Stinner914cde82016-03-19 01:03:51 +0100358.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
359
360 Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
Daniel Hahlerfdcd53f2020-03-12 18:09:30 +0100361 :exc:`ResourceWarning` and it passes *source* to :func:`warnings.WarningMessage`.
Victor Stinner914cde82016-03-19 01:03:51 +0100362
363 .. versionadded:: 3.6
364
365
Antoine Pitrou550ff722014-09-30 21:56:10 +0200366Querying the error indicator
367============================
368
369.. c:function:: PyObject* PyErr_Occurred()
370
371 Test whether the error indicator is set. If set, return the exception *type*
372 (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200373 functions or to :c:func:`PyErr_Restore`). If not set, return ``NULL``. You do not
Antoine Pitrou550ff722014-09-30 21:56:10 +0200374 own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
375 it.
376
Victor Stinnerd12d0e72019-11-07 12:42:07 +0100377 The caller must hold the GIL.
378
Antoine Pitrou550ff722014-09-30 21:56:10 +0200379 .. note::
380
381 Do not compare the return value to a specific exception; use
382 :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could
383 easily fail since the exception may be an instance instead of a class, in the
Benjamin Peterson610bc6a2015-01-13 09:20:31 -0500384 case of a class exception, or it may be a subclass of the expected exception.)
Antoine Pitrou550ff722014-09-30 21:56:10 +0200385
386
387.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
388
389 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This
390 should only be called when an exception is actually set; a memory access
391 violation will occur if no exception has been raised.
392
393
394.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
395
396 Return true if the *given* exception matches the exception type in *exc*. If
397 *exc* is a class object, this also returns true when *given* is an instance
398 of a subclass. If *exc* is a tuple, all exception types in the tuple (and
399 recursively in subtuples) are searched for a match.
400
401
402.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
403
404 Retrieve the error indicator into three variables whose addresses are passed.
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200405 If the error indicator is not set, set all three variables to ``NULL``. If it is
Antoine Pitrou550ff722014-09-30 21:56:10 +0200406 set, it will be cleared and you own a reference to each object retrieved. The
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200407 value and traceback object may be ``NULL`` even when the type object is not.
Antoine Pitrou550ff722014-09-30 21:56:10 +0200408
409 .. note::
410
411 This function is normally only used by code that needs to catch exceptions or
412 by code that needs to save and restore the error indicator temporarily, e.g.::
413
414 {
Serhiy Storchaka4398c122016-12-25 16:22:23 +0200415 PyObject *type, *value, *traceback;
Antoine Pitrou550ff722014-09-30 21:56:10 +0200416 PyErr_Fetch(&type, &value, &traceback);
417
418 /* ... code that might produce other errors ... */
419
420 PyErr_Restore(type, value, traceback);
421 }
422
423
424.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
425
426 Set the error indicator from the three objects. If the error indicator is
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200427 already set, it is cleared first. If the objects are ``NULL``, the error
428 indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or
Antoine Pitrou550ff722014-09-30 21:56:10 +0200429 traceback. The exception type should be a class. Do not pass an invalid
430 exception type or value. (Violating these rules will cause subtle problems
431 later.) This call takes away a reference to each object: you must own a
432 reference to each object before the call and after the call you no longer own
433 these references. (If you don't understand this, don't use this function. I
434 warned you.)
435
436 .. note::
437
438 This function is normally only used by code that needs to save and restore the
439 error indicator temporarily. Use :c:func:`PyErr_Fetch` to save the current
440 error indicator.
441
442
443.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
444
445 Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
446 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
447 not an instance of the same class. This function can be used to instantiate
448 the class in that case. If the values are already normalized, nothing happens.
449 The delayed normalization is implemented to improve performance.
450
451 .. note::
452
453 This function *does not* implicitly set the ``__traceback__``
454 attribute on the exception value. If setting the traceback
455 appropriately is desired, the following additional snippet is needed::
456
457 if (tb != NULL) {
458 PyException_SetTraceback(val, tb);
459 }
460
461
462.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
463
464 Retrieve the exception info, as known from ``sys.exc_info()``. This refers
465 to an exception that was *already caught*, not to an exception that was
466 freshly raised. Returns new references for the three objects, any of which
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200467 may be ``NULL``. Does not modify the exception info state.
Antoine Pitrou550ff722014-09-30 21:56:10 +0200468
469 .. note::
470
471 This function is not normally used by code that wants to handle exceptions.
472 Rather, it can be used when code needs to save and restore the exception
473 state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the
474 exception state.
475
476 .. versionadded:: 3.3
477
478
479.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
480
481 Set the exception info, as known from ``sys.exc_info()``. This refers
482 to an exception that was *already caught*, not to an exception that was
483 freshly raised. This function steals the references of the arguments.
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200484 To clear the exception state, pass ``NULL`` for all three arguments.
Antoine Pitrou550ff722014-09-30 21:56:10 +0200485 For general rules about the three arguments, see :c:func:`PyErr_Restore`.
486
487 .. note::
488
489 This function is not normally used by code that wants to handle exceptions.
490 Rather, it can be used when code needs to save and restore the exception
491 state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception
492 state.
493
494 .. versionadded:: 3.3
495
496
497Signal Handling
498===============
499
500
Georg Brandl60203b42010-10-06 10:11:56 +0000501.. c:function:: int PyErr_CheckSignals()
Georg Brandl116aa622007-08-15 14:28:22 +0000502
503 .. index::
504 module: signal
505 single: SIGINT
506 single: KeyboardInterrupt (built-in exception)
507
Antoine Pitrouba251c22021-03-11 23:35:45 +0100508 This function interacts with Python's signal handling.
509
510 If the function is called from the main thread and under the main Python
511 interpreter, it checks whether a signal has been sent to the processes
512 and if so, invokes the corresponding signal handler. If the :mod:`signal`
513 module is supported, this can invoke a signal handler written in Python.
514
515 The function attemps to handle all pending signals, and then returns ``0``.
516 However, if a Python signal handler raises an exception, the error
517 indicator is set and the function returns ``-1`` immediately (such that
518 other pending signals may not have been handled yet: they will be on the
519 next :c:func:`PyErr_CheckSignals()` invocation).
520
521 If the function is called from a non-main thread, or under a non-main
522 Python interpreter, it does nothing and returns ``0``.
523
524 This function can be called by long-running C code that wants to
525 be interruptible by user requests (such as by pressing Ctrl-C).
526
527 .. note::
528 The default Python signal handler for :const:`SIGINT` raises the
529 :exc:`KeyboardInterrupt` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531
Georg Brandl60203b42010-10-06 10:11:56 +0000532.. c:function:: void PyErr_SetInterrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534 .. index::
Antoine Pitrouba251c22021-03-11 23:35:45 +0100535 module: signal
Georg Brandl116aa622007-08-15 14:28:22 +0000536 single: SIGINT
537 single: KeyboardInterrupt (built-in exception)
538
Antoine Pitrouba251c22021-03-11 23:35:45 +0100539 Simulate the effect of a :const:`SIGINT` signal arriving.
540 This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
Antoine Pitrouba251c22021-03-11 23:35:45 +0100542 .. note::
543 This function is async-signal-safe. It can be called without
544 the :term:`GIL` and from a C signal handler.
545
546
547.. c:function:: int PyErr_SetInterruptEx(int signum)
548
549 .. index::
550 module: signal
551 single: KeyboardInterrupt (built-in exception)
552
553 Simulate the effect of a signal arriving. The next time
554 :c:func:`PyErr_CheckSignals` is called, the Python signal handler for
555 the given signal number will be called.
556
557 This function can be called by C code that sets up its own signal handling
558 and wants Python signal handlers to be invoked as expected when an
559 interruption is requested (for example when the user presses Ctrl-C
560 to interrupt an operation).
561
562 If the given signal isn't handled by Python (it was set to
563 :data:`signal.SIG_DFL` or :data:`signal.SIG_IGN`), it will be ignored.
564
565 If *signum* is outside of the allowed range of signal numbers, ``-1``
566 is returned. Otherwise, ``0`` is returned. The error indicator is
567 never changed by this function.
568
569 .. note::
570 This function is async-signal-safe. It can be called without
571 the :term:`GIL` and from a C signal handler.
572
573 .. versionadded:: 3.10
574
Georg Brandl116aa622007-08-15 14:28:22 +0000575
Georg Brandl60203b42010-10-06 10:11:56 +0000576.. c:function:: int PySignal_SetWakeupFd(int fd)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000577
Victor Stinner11517102014-07-29 23:31:34 +0200578 This utility function specifies a file descriptor to which the signal number
579 is written as a single byte whenever a signal is received. *fd* must be
580 non-blocking. It returns the previous such file descriptor.
581
582 The value ``-1`` disables the feature; this is the initial state.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000583 This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
584 error checking. *fd* should be a valid file descriptor. The function should
585 only be called from the main thread.
586
Victor Stinner11517102014-07-29 23:31:34 +0200587 .. versionchanged:: 3.5
588 On Windows, the function now also supports socket handles.
589
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000590
Antoine Pitrou550ff722014-09-30 21:56:10 +0200591Exception Classes
592=================
593
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300594.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Georg Brandl325eb472011-07-13 15:59:24 +0200596 This utility function creates and returns a new exception class. The *name*
Georg Brandl116aa622007-08-15 14:28:22 +0000597 argument must be the name of the new exception, a C string of the form
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200598 ``module.classname``. The *base* and *dict* arguments are normally ``NULL``.
Georg Brandl325eb472011-07-13 15:59:24 +0200599 This creates a class object derived from :exc:`Exception` (accessible in C as
Georg Brandl60203b42010-10-06 10:11:56 +0000600 :c:data:`PyExc_Exception`).
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602 The :attr:`__module__` attribute of the new class is set to the first part (up
603 to the last dot) of the *name* argument, and the class name is set to the last
604 part (after the last dot). The *base* argument can be used to specify alternate
605 base classes; it can either be only one class or a tuple of classes. The *dict*
606 argument can be used to specify a dictionary of class variables and methods.
607
608
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300609.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000610
Georg Brandl60203b42010-10-06 10:11:56 +0000611 Same as :c:func:`PyErr_NewException`, except that the new exception class can
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200612 easily be given a docstring: If *doc* is non-``NULL``, it will be used as the
Georg Brandl1e28a272009-12-28 08:41:01 +0000613 docstring for the exception class.
614
615 .. versionadded:: 3.2
616
617
Georg Brandlab6f2f62009-03-31 04:16:10 +0000618Exception Objects
619=================
620
Georg Brandl60203b42010-10-06 10:11:56 +0000621.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000622
623 Return the traceback associated with the exception as a new reference, as
624 accessible from Python through :attr:`__traceback__`. If there is no
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200625 traceback associated, this returns ``NULL``.
Georg Brandlab6f2f62009-03-31 04:16:10 +0000626
627
Georg Brandl60203b42010-10-06 10:11:56 +0000628.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000629
630 Set the traceback associated with the exception to *tb*. Use ``Py_None`` to
631 clear it.
632
633
Georg Brandl60203b42010-10-06 10:11:56 +0000634.. c:function:: PyObject* PyException_GetContext(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000635
636 Return the context (another exception instance during whose handling *ex* was
637 raised) associated with the exception as a new reference, as accessible from
638 Python through :attr:`__context__`. If there is no context associated, this
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200639 returns ``NULL``.
Georg Brandlab6f2f62009-03-31 04:16:10 +0000640
641
Georg Brandl60203b42010-10-06 10:11:56 +0000642.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000643
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200644 Set the context associated with the exception to *ctx*. Use ``NULL`` to clear
Georg Brandlab6f2f62009-03-31 04:16:10 +0000645 it. There is no type check to make sure that *ctx* is an exception instance.
646 This steals a reference to *ctx*.
647
648
Georg Brandl60203b42010-10-06 10:11:56 +0000649.. c:function:: PyObject* PyException_GetCause(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000650
Nick Coghlanab7bf212012-02-26 17:49:52 +1000651 Return the cause (either an exception instance, or :const:`None`,
652 set by ``raise ... from ...``) associated with the exception as a new
653 reference, as accessible from Python through :attr:`__cause__`.
654
Georg Brandlab6f2f62009-03-31 04:16:10 +0000655
Larry Hastings3732ed22014-03-15 21:13:56 -0700656.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000657
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200658 Set the cause associated with the exception to *cause*. Use ``NULL`` to clear
Larry Hastings3732ed22014-03-15 21:13:56 -0700659 it. There is no type check to make sure that *cause* is either an exception
660 instance or :const:`None`. This steals a reference to *cause*.
Nick Coghlanab7bf212012-02-26 17:49:52 +1000661
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700662 :attr:`__suppress_context__` is implicitly set to ``True`` by this function.
Georg Brandlab6f2f62009-03-31 04:16:10 +0000663
664
Georg Brandl5a932652010-11-23 07:54:19 +0000665.. _unicodeexceptions:
666
667Unicode Exception Objects
668=========================
669
670The following functions are used to create and modify Unicode exceptions from C.
671
672.. 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)
673
674 Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000675 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
676 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000677
678.. c:function:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
679
680 Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000681 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
682 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000683
Inada Naoki46e19b62020-08-07 16:31:53 +0900684 .. deprecated:: 3.3 3.11
685
686 ``Py_UNICODE`` is deprecated since Python 3.3. Please migrate to
687 ``PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns", ...)``.
688
Georg Brandl5a932652010-11-23 07:54:19 +0000689.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
690
691 Create a :class:`UnicodeTranslateError` object with the attributes *object*,
Martin Panter6245cb32016-04-15 02:14:19 +0000692 *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string.
Georg Brandl5a932652010-11-23 07:54:19 +0000693
Inada Naoki46e19b62020-08-07 16:31:53 +0900694 .. deprecated:: 3.3 3.11
695
696 ``Py_UNICODE`` is deprecated since Python 3.3. Please migrate to
697 ``PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", ...)``.
698
Georg Brandl5a932652010-11-23 07:54:19 +0000699.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
700 PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
701
702 Return the *encoding* attribute of the given exception object.
703
704.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
705 PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
706 PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
707
708 Return the *object* attribute of the given exception object.
709
710.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
711 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
712 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
713
714 Get the *start* attribute of the given exception object and place it into
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200715 *\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` on
Georg Brandl5a932652010-11-23 07:54:19 +0000716 failure.
717
718.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
719 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
720 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
721
722 Set the *start* attribute of the given exception object to *start*. Return
723 ``0`` on success, ``-1`` on failure.
724
725.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
726 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
727 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
728
729 Get the *end* attribute of the given exception object and place it into
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200730 *\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on
Georg Brandl5a932652010-11-23 07:54:19 +0000731 failure.
732
733.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
734 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
735 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
736
737 Set the *end* attribute of the given exception object to *end*. Return ``0``
738 on success, ``-1`` on failure.
739
740.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
741 PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
742 PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
743
744 Return the *reason* attribute of the given exception object.
745
746.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
747 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
748 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
749
750 Set the *reason* attribute of the given exception object to *reason*. Return
751 ``0`` on success, ``-1`` on failure.
752
753
Jeroen Demeyer9a13a382019-11-12 14:08:00 +0100754.. _recursion:
755
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000756Recursion Control
757=================
758
759These two functions provide a way to perform safe recursive calls at the C
760level, both in the core and in extension modules. They are needed if the
761recursive code does not necessarily invoke Python code (which tracks its
762recursion depth automatically).
Jeroen Demeyer9a13a382019-11-12 14:08:00 +0100763They are also not needed for *tp_call* implementations
764because the :ref:`call protocol <call>` takes care of recursion handling.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000765
Serhiy Storchaka5fa22fc2015-06-21 16:26:28 +0300766.. c:function:: int Py_EnterRecursiveCall(const char *where)
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000767
768 Marks a point where a recursive C-level call is about to be performed.
769
Ezio Melottif1064492011-10-19 11:06:26 +0300770 If :const:`USE_STACKCHECK` is defined, this function checks if the OS
Georg Brandl60203b42010-10-06 10:11:56 +0000771 stack overflowed using :c:func:`PyOS_CheckStack`. In this is the case, it
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000772 sets a :exc:`MemoryError` and returns a nonzero value.
773
774 The function then checks if the recursion limit is reached. If this is the
Yury Selivanovf488fb42015-07-03 01:04:23 -0400775 case, a :exc:`RecursionError` is set and a nonzero value is returned.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000776 Otherwise, zero is returned.
777
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +0100778 *where* should be a UTF-8 encoded string such as ``" in instance check"`` to
779 be concatenated to the :exc:`RecursionError` message caused by the recursion
Yury Selivanovf488fb42015-07-03 01:04:23 -0400780 depth limit.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000781
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +0100782 .. versionchanged:: 3.9
783 This function is now also available in the limited API.
784
785.. c:function:: void Py_LeaveRecursiveCall(void)
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000786
Georg Brandl60203b42010-10-06 10:11:56 +0000787 Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each
788 *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000789
Victor Stinnerf4b1e3d2019-11-04 19:48:34 +0100790 .. versionchanged:: 3.9
791 This function is now also available in the limited API.
792
Antoine Pitrou39668f52013-08-01 21:12:45 +0200793Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000794special recursion handling. In addition to protecting the stack,
Antoine Pitrou39668f52013-08-01 21:12:45 +0200795:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000796following two functions facilitate this functionality. Effectively,
797these are the C equivalent to :func:`reprlib.recursive_repr`.
798
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000799.. c:function:: int Py_ReprEnter(PyObject *object)
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000800
Antoine Pitrou39668f52013-08-01 21:12:45 +0200801 Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000802 detect cycles.
803
804 If the object has already been processed, the function returns a
Antoine Pitrou39668f52013-08-01 21:12:45 +0200805 positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000806 should return a string object indicating a cycle. As examples,
807 :class:`dict` objects return ``{...}`` and :class:`list` objects
808 return ``[...]``.
809
810 The function will return a negative integer if the recursion limit
Antoine Pitrou39668f52013-08-01 21:12:45 +0200811 is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000812 typically return ``NULL``.
813
Antoine Pitrou39668f52013-08-01 21:12:45 +0200814 Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000815 implementation can continue normally.
816
817.. c:function:: void Py_ReprLeave(PyObject *object)
818
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000819 Ends a :c:func:`Py_ReprEnter`. Must be called once for each
820 invocation of :c:func:`Py_ReprEnter` that returns zero.
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000821
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000822
Georg Brandl116aa622007-08-15 14:28:22 +0000823.. _standardexceptions:
824
825Standard Exceptions
826===================
827
828All standard Python exceptions are available as global variables whose names are
829``PyExc_`` followed by the Python exception name. These have the type
Victor Stinner474652f2020-08-13 22:11:50 +0200830:c:type:`PyObject*`; they are all class objects. For completeness, here are all
Georg Brandl116aa622007-08-15 14:28:22 +0000831the variables:
832
cocoatomoe8c76312017-04-02 19:45:40 +0900833.. index::
834 single: PyExc_BaseException
835 single: PyExc_Exception
836 single: PyExc_ArithmeticError
837 single: PyExc_AssertionError
838 single: PyExc_AttributeError
839 single: PyExc_BlockingIOError
840 single: PyExc_BrokenPipeError
841 single: PyExc_BufferError
842 single: PyExc_ChildProcessError
843 single: PyExc_ConnectionAbortedError
844 single: PyExc_ConnectionError
845 single: PyExc_ConnectionRefusedError
846 single: PyExc_ConnectionResetError
847 single: PyExc_EOFError
848 single: PyExc_FileExistsError
849 single: PyExc_FileNotFoundError
850 single: PyExc_FloatingPointError
851 single: PyExc_GeneratorExit
852 single: PyExc_ImportError
853 single: PyExc_IndentationError
854 single: PyExc_IndexError
855 single: PyExc_InterruptedError
856 single: PyExc_IsADirectoryError
857 single: PyExc_KeyError
858 single: PyExc_KeyboardInterrupt
859 single: PyExc_LookupError
860 single: PyExc_MemoryError
861 single: PyExc_ModuleNotFoundError
862 single: PyExc_NameError
863 single: PyExc_NotADirectoryError
864 single: PyExc_NotImplementedError
865 single: PyExc_OSError
866 single: PyExc_OverflowError
867 single: PyExc_PermissionError
868 single: PyExc_ProcessLookupError
869 single: PyExc_RecursionError
870 single: PyExc_ReferenceError
871 single: PyExc_RuntimeError
872 single: PyExc_StopAsyncIteration
873 single: PyExc_StopIteration
874 single: PyExc_SyntaxError
875 single: PyExc_SystemError
876 single: PyExc_SystemExit
877 single: PyExc_TabError
878 single: PyExc_TimeoutError
879 single: PyExc_TypeError
880 single: PyExc_UnboundLocalError
881 single: PyExc_UnicodeDecodeError
882 single: PyExc_UnicodeEncodeError
883 single: PyExc_UnicodeError
884 single: PyExc_UnicodeTranslateError
885 single: PyExc_ValueError
886 single: PyExc_ZeroDivisionError
887
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200888+-----------------------------------------+---------------------------------+----------+
889| C Name | Python Name | Notes |
890+=========================================+=================================+==========+
891| :c:data:`PyExc_BaseException` | :exc:`BaseException` | \(1) |
892+-----------------------------------------+---------------------------------+----------+
893| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) |
894+-----------------------------------------+---------------------------------+----------+
895| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) |
896+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200897| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | |
898+-----------------------------------------+---------------------------------+----------+
899| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | |
900+-----------------------------------------+---------------------------------+----------+
901| :c:data:`PyExc_BlockingIOError` | :exc:`BlockingIOError` | |
902+-----------------------------------------+---------------------------------+----------+
903| :c:data:`PyExc_BrokenPipeError` | :exc:`BrokenPipeError` | |
904+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900905| :c:data:`PyExc_BufferError` | :exc:`BufferError` | |
906+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200907| :c:data:`PyExc_ChildProcessError` | :exc:`ChildProcessError` | |
908+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200909| :c:data:`PyExc_ConnectionAbortedError` | :exc:`ConnectionAbortedError` | |
910+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900911| :c:data:`PyExc_ConnectionError` | :exc:`ConnectionError` | |
912+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200913| :c:data:`PyExc_ConnectionRefusedError` | :exc:`ConnectionRefusedError` | |
914+-----------------------------------------+---------------------------------+----------+
915| :c:data:`PyExc_ConnectionResetError` | :exc:`ConnectionResetError` | |
916+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900917| :c:data:`PyExc_EOFError` | :exc:`EOFError` | |
918+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200919| :c:data:`PyExc_FileExistsError` | :exc:`FileExistsError` | |
920+-----------------------------------------+---------------------------------+----------+
921| :c:data:`PyExc_FileNotFoundError` | :exc:`FileNotFoundError` | |
922+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200923| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | |
924+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900925| :c:data:`PyExc_GeneratorExit` | :exc:`GeneratorExit` | |
926+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200927| :c:data:`PyExc_ImportError` | :exc:`ImportError` | |
928+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900929| :c:data:`PyExc_IndentationError` | :exc:`IndentationError` | |
Eric Snowc9432652016-09-07 15:42:32 -0700930+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200931| :c:data:`PyExc_IndexError` | :exc:`IndexError` | |
932+-----------------------------------------+---------------------------------+----------+
933| :c:data:`PyExc_InterruptedError` | :exc:`InterruptedError` | |
934+-----------------------------------------+---------------------------------+----------+
935| :c:data:`PyExc_IsADirectoryError` | :exc:`IsADirectoryError` | |
936+-----------------------------------------+---------------------------------+----------+
937| :c:data:`PyExc_KeyError` | :exc:`KeyError` | |
938+-----------------------------------------+---------------------------------+----------+
939| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | |
940+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900941| :c:data:`PyExc_LookupError` | :exc:`LookupError` | \(1) |
942+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200943| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | |
944+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900945| :c:data:`PyExc_ModuleNotFoundError` | :exc:`ModuleNotFoundError` | |
946+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200947| :c:data:`PyExc_NameError` | :exc:`NameError` | |
948+-----------------------------------------+---------------------------------+----------+
949| :c:data:`PyExc_NotADirectoryError` | :exc:`NotADirectoryError` | |
950+-----------------------------------------+---------------------------------+----------+
951| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | |
952+-----------------------------------------+---------------------------------+----------+
953| :c:data:`PyExc_OSError` | :exc:`OSError` | \(1) |
954+-----------------------------------------+---------------------------------+----------+
955| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | |
956+-----------------------------------------+---------------------------------+----------+
957| :c:data:`PyExc_PermissionError` | :exc:`PermissionError` | |
958+-----------------------------------------+---------------------------------+----------+
959| :c:data:`PyExc_ProcessLookupError` | :exc:`ProcessLookupError` | |
960+-----------------------------------------+---------------------------------+----------+
Yury Selivanovf488fb42015-07-03 01:04:23 -0400961| :c:data:`PyExc_RecursionError` | :exc:`RecursionError` | |
962+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200963| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) |
964+-----------------------------------------+---------------------------------+----------+
965| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | |
966+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900967| :c:data:`PyExc_StopAsyncIteration` | :exc:`StopAsyncIteration` | |
968+-----------------------------------------+---------------------------------+----------+
969| :c:data:`PyExc_StopIteration` | :exc:`StopIteration` | |
970+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200971| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | |
972+-----------------------------------------+---------------------------------+----------+
973| :c:data:`PyExc_SystemError` | :exc:`SystemError` | |
974+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200975| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | |
976+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900977| :c:data:`PyExc_TabError` | :exc:`TabError` | |
978+-----------------------------------------+---------------------------------+----------+
979| :c:data:`PyExc_TimeoutError` | :exc:`TimeoutError` | |
980+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200981| :c:data:`PyExc_TypeError` | :exc:`TypeError` | |
982+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900983| :c:data:`PyExc_UnboundLocalError` | :exc:`UnboundLocalError` | |
984+-----------------------------------------+---------------------------------+----------+
985| :c:data:`PyExc_UnicodeDecodeError` | :exc:`UnicodeDecodeError` | |
986+-----------------------------------------+---------------------------------+----------+
987| :c:data:`PyExc_UnicodeEncodeError` | :exc:`UnicodeEncodeError` | |
988+-----------------------------------------+---------------------------------+----------+
989| :c:data:`PyExc_UnicodeError` | :exc:`UnicodeError` | |
990+-----------------------------------------+---------------------------------+----------+
991| :c:data:`PyExc_UnicodeTranslateError` | :exc:`UnicodeTranslateError` | |
992+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200993| :c:data:`PyExc_ValueError` | :exc:`ValueError` | |
994+-----------------------------------------+---------------------------------+----------+
995| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | |
996+-----------------------------------------+---------------------------------+----------+
997
998.. versionadded:: 3.3
999 :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
1000 :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
1001 :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
1002 :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
1003 :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
1004 :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
1005 :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
1006 and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
1007
Yury Selivanovf488fb42015-07-03 01:04:23 -04001008.. versionadded:: 3.5
cocoatomoe8c76312017-04-02 19:45:40 +09001009 :c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`.
Yury Selivanovf488fb42015-07-03 01:04:23 -04001010
cocoatomoe8c76312017-04-02 19:45:40 +09001011.. versionadded:: 3.6
1012 :c:data:`PyExc_ModuleNotFoundError`.
Antoine Pitrou9a4a3422011-10-12 18:28:01 +02001013
1014These are compatibility aliases to :c:data:`PyExc_OSError`:
1015
cocoatomoe8c76312017-04-02 19:45:40 +09001016.. index::
1017 single: PyExc_EnvironmentError
1018 single: PyExc_IOError
1019 single: PyExc_WindowsError
1020
Antoine Pitrou9a4a3422011-10-12 18:28:01 +02001021+-------------------------------------+----------+
1022| C Name | Notes |
1023+=====================================+==========+
1024| :c:data:`PyExc_EnvironmentError` | |
1025+-------------------------------------+----------+
1026| :c:data:`PyExc_IOError` | |
1027+-------------------------------------+----------+
1028| :c:data:`PyExc_WindowsError` | \(3) |
1029+-------------------------------------+----------+
1030
1031.. versionchanged:: 3.3
1032 These aliases used to be separate exception types.
1033
Georg Brandl116aa622007-08-15 14:28:22 +00001034Notes:
1035
1036(1)
1037 This is a base class for other standard exceptions.
1038
1039(2)
Georg Brandl116aa622007-08-15 14:28:22 +00001040 Only defined on Windows; protect code that uses this by testing that the
1041 preprocessor macro ``MS_WINDOWS`` is defined.
cocoatomoe8c76312017-04-02 19:45:40 +09001042
delirious-lettuce3378b202017-05-19 14:37:57 -06001043.. _standardwarningcategories:
cocoatomoeaeda642017-04-15 11:06:02 +09001044
1045Standard Warning Categories
1046===========================
cocoatomoe8c76312017-04-02 19:45:40 +09001047
1048All standard Python warning categories are available as global variables whose
1049names are ``PyExc_`` followed by the Python exception name. These have the type
Victor Stinner474652f2020-08-13 22:11:50 +02001050:c:type:`PyObject*`; they are all class objects. For completeness, here are all
cocoatomoe8c76312017-04-02 19:45:40 +09001051the variables:
1052
1053.. index::
1054 single: PyExc_Warning
1055 single: PyExc_BytesWarning
delirious-lettuce3378b202017-05-19 14:37:57 -06001056 single: PyExc_DeprecationWarning
cocoatomoe8c76312017-04-02 19:45:40 +09001057 single: PyExc_FutureWarning
1058 single: PyExc_ImportWarning
1059 single: PyExc_PendingDeprecationWarning
1060 single: PyExc_ResourceWarning
1061 single: PyExc_RuntimeWarning
1062 single: PyExc_SyntaxWarning
1063 single: PyExc_UnicodeWarning
1064 single: PyExc_UserWarning
1065
1066+------------------------------------------+---------------------------------+----------+
1067| C Name | Python Name | Notes |
1068+==========================================+=================================+==========+
1069| :c:data:`PyExc_Warning` | :exc:`Warning` | \(1) |
1070+------------------------------------------+---------------------------------+----------+
1071| :c:data:`PyExc_BytesWarning` | :exc:`BytesWarning` | |
1072+------------------------------------------+---------------------------------+----------+
1073| :c:data:`PyExc_DeprecationWarning` | :exc:`DeprecationWarning` | |
1074+------------------------------------------+---------------------------------+----------+
1075| :c:data:`PyExc_FutureWarning` | :exc:`FutureWarning` | |
1076+------------------------------------------+---------------------------------+----------+
1077| :c:data:`PyExc_ImportWarning` | :exc:`ImportWarning` | |
1078+------------------------------------------+---------------------------------+----------+
delirious-lettuce3378b202017-05-19 14:37:57 -06001079| :c:data:`PyExc_PendingDeprecationWarning`| :exc:`PendingDeprecationWarning`| |
cocoatomoe8c76312017-04-02 19:45:40 +09001080+------------------------------------------+---------------------------------+----------+
1081| :c:data:`PyExc_ResourceWarning` | :exc:`ResourceWarning` | |
1082+------------------------------------------+---------------------------------+----------+
1083| :c:data:`PyExc_RuntimeWarning` | :exc:`RuntimeWarning` | |
1084+------------------------------------------+---------------------------------+----------+
1085| :c:data:`PyExc_SyntaxWarning` | :exc:`SyntaxWarning` | |
1086+------------------------------------------+---------------------------------+----------+
1087| :c:data:`PyExc_UnicodeWarning` | :exc:`UnicodeWarning` | |
1088+------------------------------------------+---------------------------------+----------+
1089| :c:data:`PyExc_UserWarning` | :exc:`UserWarning` | |
1090+------------------------------------------+---------------------------------+----------+
1091
1092.. versionadded:: 3.2
1093 :c:data:`PyExc_ResourceWarning`.
1094
1095Notes:
1096
1097(1)
1098 This is a base class for other standard warning categories.