blob: 13f0aff1cf99b6321eb1caaf249b7d2bacd84089 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _exceptionhandling:
5
6******************
7Exception Handling
8******************
9
10The functions described in this chapter will let you handle and raise Python
11exceptions. It is important to understand some of the basics of Python
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
16indicator, usually *NULL* if they are supposed to return a pointer, or ``-1``
17if 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
22of those pointers can be NULL if non-set (although some combinations are
23forbidden, for example you can't have a non-NULL traceback if the exception
24type is NULL).
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
Antoine Pitrou550ff722014-09-30 21:56:10 +020075 This utility function prints a warning message to ``sys.stderr`` when an
76 exception has been set but it is impossible for the interpreter to actually
77 raise the exception. It is used, for example, when an exception occurs in an
78 :meth:`__del__` method.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Antoine Pitrou550ff722014-09-30 21:56:10 +020080 The function is called with a single argument *obj* that identifies the context
Martin Panter3263f682016-02-28 03:16:11 +000081 in which the unraisable exception occurred. If possible,
82 the repr of *obj* will be printed in the warning message.
Georg Brandl116aa622007-08-15 14:28:22 +000083
84
Antoine Pitrou550ff722014-09-30 21:56:10 +020085Raising exceptions
86==================
Georg Brandl116aa622007-08-15 14:28:22 +000087
Antoine Pitrou550ff722014-09-30 21:56:10 +020088These functions help you set the current thread's error indicator.
89For convenience, some of these functions will always return a
90NULL pointer for use in a ``return`` statement.
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020091
92
Georg Brandl60203b42010-10-06 10:11:56 +000093.. c:function:: void PyErr_SetString(PyObject *type, const char *message)
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 This is the most common way to set the error indicator. The first argument
96 specifies the exception type; it is normally one of the standard exceptions,
Georg Brandl60203b42010-10-06 10:11:56 +000097 e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count.
Victor Stinner257d38f2010-10-09 10:12:11 +000098 The second argument is an error message; it is decoded from ``'utf-8``'.
Georg Brandl116aa622007-08-15 14:28:22 +000099
100
Georg Brandl60203b42010-10-06 10:11:56 +0000101.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Georg Brandl60203b42010-10-06 10:11:56 +0000103 This function is similar to :c:func:`PyErr_SetString` but lets you specify an
Georg Brandl116aa622007-08-15 14:28:22 +0000104 arbitrary Python object for the "value" of the exception.
105
106
Georg Brandl60203b42010-10-06 10:11:56 +0000107.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Antoine Pitroua66e0292010-11-27 20:40:43 +0000109 This function sets the error indicator and returns *NULL*. *exception*
110 should be a Python exception class. The *format* and subsequent
111 parameters help format the error message; they have the same meaning and
Victor Stinnerb1dbd102010-12-28 11:02:46 +0000112 values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
Victor Stinner555a24f2010-12-27 01:49:26 +0000113 string.
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000114
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Antoine Pitrou0676a402014-09-30 21:16:27 +0200116.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
117
Georg Brandl93a56cd2014-10-30 22:25:41 +0100118 Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather
Antoine Pitrou0676a402014-09-30 21:16:27 +0200119 than a variable number of arguments.
120
121 .. versionadded:: 3.5
122
123
Georg Brandl60203b42010-10-06 10:11:56 +0000124.. c:function:: void PyErr_SetNone(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126 This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
127
128
Georg Brandl60203b42010-10-06 10:11:56 +0000129.. c:function:: int PyErr_BadArgument()
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
132 *message* indicates that a built-in operation was invoked with an illegal
133 argument. It is mostly for internal use.
134
135
Georg Brandl60203b42010-10-06 10:11:56 +0000136.. c:function:: PyObject* PyErr_NoMemory()
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138 This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL*
139 so an object allocation function can write ``return PyErr_NoMemory();`` when it
140 runs out of memory.
141
142
Georg Brandl60203b42010-10-06 10:11:56 +0000143.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145 .. index:: single: strerror()
146
147 This is a convenience function to raise an exception when a C library function
Georg Brandl60203b42010-10-06 10:11:56 +0000148 has returned an error and set the C variable :c:data:`errno`. It constructs a
149 tuple object whose first item is the integer :c:data:`errno` value and whose
150 second item is the corresponding error message (gotten from :c:func:`strerror`),
Georg Brandl116aa622007-08-15 14:28:22 +0000151 and then calls ``PyErr_SetObject(type, object)``. On Unix, when the
Georg Brandl60203b42010-10-06 10:11:56 +0000152 :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call,
153 this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator,
Georg Brandl116aa622007-08-15 14:28:22 +0000154 leaves it set to that. The function always returns *NULL*, so a wrapper
155 function around a system call can write ``return PyErr_SetFromErrno(type);``
156 when the system call returns an error.
157
158
Georg Brandl991fc572013-04-14 11:12:16 +0200159.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Georg Brandl60203b42010-10-06 10:11:56 +0000161 Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
Georg Brandl991fc572013-04-14 11:12:16 +0200162 *filenameObject* is not *NULL*, it is passed to the constructor of *type* as
Andrew Svetlov08af0002014-04-01 01:13:30 +0300163 a third parameter. In the case of :exc:`OSError` exception,
164 this is used to define the :attr:`filename` attribute of the
Georg Brandl991fc572013-04-14 11:12:16 +0200165 exception instance.
166
167
Larry Hastingsb0827312014-02-09 22:05:19 -0800168.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
169
170 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but takes a second
171 filename object, for raising errors when a function that takes two filenames
172 fails.
173
Georg Brandldf48b972014-03-24 09:06:18 +0100174 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800175
176
Georg Brandl991fc572013-04-14 11:12:16 +0200177.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
178
179 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename
180 is given as a C string. *filename* is decoded from the filesystem encoding
Victor Stinner14e461d2013-08-26 22:28:21 +0200181 (:func:`os.fsdecode`).
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183
Georg Brandl60203b42010-10-06 10:11:56 +0000184.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186 This is a convenience function to raise :exc:`WindowsError`. If called with
Georg Brandl60203b42010-10-06 10:11:56 +0000187 *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError`
188 is used instead. It calls the Win32 function :c:func:`FormatMessage` to retrieve
189 the Windows description of error code given by *ierr* or :c:func:`GetLastError`,
Georg Brandl116aa622007-08-15 14:28:22 +0000190 then it constructs a tuple object whose first item is the *ierr* value and whose
191 second item is the corresponding error message (gotten from
Georg Brandl60203b42010-10-06 10:11:56 +0000192 :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400193 object)``. This function always returns *NULL*.
194
195 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197
Georg Brandl60203b42010-10-06 10:11:56 +0000198.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000199
Georg Brandl60203b42010-10-06 10:11:56 +0000200 Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400201 specifying the exception type to be raised.
202
203 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl60203b42010-10-06 10:11:56 +0000206.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Georg Brandl991fc572013-04-14 11:12:16 +0200208 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
209 filename is given as a C string. *filename* is decoded from the filesystem
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400210 encoding (:func:`os.fsdecode`).
211
212 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
Georg Brandl991fc572013-04-14 11:12:16 +0200215.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)
216
217 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, with an
218 additional parameter specifying the exception type to be raised.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400219
220 .. availability:: Windows.
Georg Brandl991fc572013-04-14 11:12:16 +0200221
222
Larry Hastingsb0827312014-02-09 22:05:19 -0800223.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
224
225 Similar to :c:func:`PyErr_SetExcFromWindowsErrWithFilenameObject`,
226 but accepts a second filename object.
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400227
228 .. availability:: Windows.
Larry Hastingsb0827312014-02-09 22:05:19 -0800229
Georg Brandldf48b972014-03-24 09:06:18 +0100230 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800231
232
Georg Brandl991fc572013-04-14 11:12:16 +0200233.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Georg Brandl60203b42010-10-06 10:11:56 +0000235 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400236 parameter specifying the exception type to be raised.
237
238 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Georg Brandlf4095832012-04-24 19:16:24 +0200240
Brian Curtin09b86d12012-04-17 16:57:09 -0500241.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brian Curtinbd439742012-04-16 15:14:36 -0500242
243 This is a convenience function to raise :exc:`ImportError`. *msg* will be
Brian Curtin09b86d12012-04-17 16:57:09 -0500244 set as the exception's message string. *name* and *path*, both of which can
245 be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name``
246 and ``path`` attributes.
Brian Curtinbd439742012-04-16 15:14:36 -0500247
Brian Curtinbded8942012-04-16 18:14:09 -0500248 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandlf4095832012-04-24 19:16:24 +0200250
Victor Stinner14e461d2013-08-26 22:28:21 +0200251.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000252
253 Set file, line, and offset information for the current exception. If the
254 current exception is not a :exc:`SyntaxError`, then it sets additional
255 attributes, which make the exception printing subsystem think the exception
Victor Stinner14e461d2013-08-26 22:28:21 +0200256 is a :exc:`SyntaxError`.
Benjamin Peterson2c539712010-09-20 22:42:10 +0000257
Georg Brandldf48b972014-03-24 09:06:18 +0100258 .. versionadded:: 3.4
Victor Stinner14e461d2013-08-26 22:28:21 +0200259
260
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300261.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Victor Stinner14e461d2013-08-26 22:28:21 +0200262
263 Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
264 decoded from the filesystem encoding (:func:`os.fsdecode`).
265
Georg Brandldf48b972014-03-24 09:06:18 +0100266 .. versionadded:: 3.2
Benjamin Petersonb5d23b42010-09-21 21:29:26 +0000267
Benjamin Peterson2c539712010-09-20 22:42:10 +0000268
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300269.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000270
Victor Stinner14e461d2013-08-26 22:28:21 +0200271 Like :c:func:`PyErr_SyntaxLocationEx`, but the col_offset parameter is
Benjamin Peterson2c539712010-09-20 22:42:10 +0000272 omitted.
273
274
Georg Brandl60203b42010-10-06 10:11:56 +0000275.. c:function:: void PyErr_BadInternalCall()
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000277 This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
278 where *message* indicates that an internal operation (e.g. a Python/C API
279 function) was invoked with an illegal argument. It is mostly for internal
280 use.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282
Antoine Pitrou550ff722014-09-30 21:56:10 +0200283Issuing warnings
284================
285
286Use these functions to issue warnings from C code. They mirror similar
287functions exported by the Python :mod:`warnings` module. They normally
288print a warning message to *sys.stderr*; however, it is
289also possible that the user has specified that warnings are to be turned into
290errors, and in that case they will raise an exception. It is also possible that
291the functions raise an exception because of a problem with the warning machinery.
292The return value is ``0`` if no exception is raised, or ``-1`` if an exception
293is raised. (It is not possible to determine whether a warning message is
294actually printed, nor what the reason is for the exception; this is
295intentional.) If an exception is raised, the caller should do its normal
296exception handling (for example, :c:func:`Py_DECREF` owned references and return
297an error value).
298
Georg Brandl97435162014-10-06 12:58:00 +0200299.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301 Issue a warning message. The *category* argument is a warning category (see
Martin Panter6245cb32016-04-15 02:14:19 +0000302 below) or *NULL*; the *message* argument is a UTF-8 encoded string. *stack_level* is a
Georg Brandl116aa622007-08-15 14:28:22 +0000303 positive number giving a number of stack frames; the warning will be issued from
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000304 the currently executing line of code in that stack frame. A *stack_level* of 1
Georg Brandl60203b42010-10-06 10:11:56 +0000305 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that,
Georg Brandl116aa622007-08-15 14:28:22 +0000306 and so forth.
307
cocoatomoeaeda642017-04-15 11:06:02 +0900308 Warning categories must be subclasses of :c:data:`PyExc_Warning`;
309 :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`;
310 the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard
311 Python warning categories are available as global variables whose names are
delirious-lettuce3378b202017-05-19 14:37:57 -0600312 enumerated at :ref:`standardwarningcategories`.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314 For information about warning control, see the documentation for the
315 :mod:`warnings` module and the :option:`-W` option in the command line
316 documentation. There is no C API for warning control.
317
Eric Snow46f97b82016-09-07 16:56:15 -0700318.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *msg, PyObject *name, PyObject *path)
319
320 Much like :c:func:`PyErr_SetImportError` but this function allows for
321 specifying a subclass of :exc:`ImportError` to raise.
322
Yury Selivanov3479b5f2016-11-10 13:25:26 -0500323 .. versionadded:: 3.6
Eric Snow46f97b82016-09-07 16:56:15 -0700324
Georg Brandl116aa622007-08-15 14:28:22 +0000325
Victor Stinner14e461d2013-08-26 22:28:21 +0200326.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328 Issue a warning message with explicit control over all warning attributes. This
329 is a straightforward wrapper around the Python function
330 :func:`warnings.warn_explicit`, see there for more information. The *module*
331 and *registry* arguments may be set to *NULL* to get the default effect
Victor Stinner14e461d2013-08-26 22:28:21 +0200332 described there.
333
334 .. versionadded:: 3.4
335
336
337.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
338
339 Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and
340 *module* are UTF-8 encoded strings, and *filename* is decoded from the
341 filesystem encoding (:func:`os.fsdecode`).
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343
Georg Brandl60203b42010-10-06 10:11:56 +0000344.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000345
Georg Brandl60203b42010-10-06 10:11:56 +0000346 Function similar to :c:func:`PyErr_WarnEx`, but use
Victor Stinner555a24f2010-12-27 01:49:26 +0000347 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
348 an ASCII-encoded string.
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000349
350 .. versionadded:: 3.2
351
Georg Brandlf4095832012-04-24 19:16:24 +0200352
Victor Stinner914cde82016-03-19 01:03:51 +0100353.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
354
355 Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
356 :exc:`ResourceWarning` and pass *source* to :func:`warnings.WarningMessage`.
357
358 .. versionadded:: 3.6
359
360
Antoine Pitrou550ff722014-09-30 21:56:10 +0200361Querying the error indicator
362============================
363
364.. c:function:: PyObject* PyErr_Occurred()
365
366 Test whether the error indicator is set. If set, return the exception *type*
367 (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
368 functions or to :c:func:`PyErr_Restore`). If not set, return *NULL*. You do not
369 own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
370 it.
371
372 .. note::
373
374 Do not compare the return value to a specific exception; use
375 :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could
376 easily fail since the exception may be an instance instead of a class, in the
Benjamin Peterson610bc6a2015-01-13 09:20:31 -0500377 case of a class exception, or it may be a subclass of the expected exception.)
Antoine Pitrou550ff722014-09-30 21:56:10 +0200378
379
380.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
381
382 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This
383 should only be called when an exception is actually set; a memory access
384 violation will occur if no exception has been raised.
385
386
387.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
388
389 Return true if the *given* exception matches the exception type in *exc*. If
390 *exc* is a class object, this also returns true when *given* is an instance
391 of a subclass. If *exc* is a tuple, all exception types in the tuple (and
392 recursively in subtuples) are searched for a match.
393
394
395.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
396
397 Retrieve the error indicator into three variables whose addresses are passed.
398 If the error indicator is not set, set all three variables to *NULL*. If it is
399 set, it will be cleared and you own a reference to each object retrieved. The
400 value and traceback object may be *NULL* even when the type object is not.
401
402 .. note::
403
404 This function is normally only used by code that needs to catch exceptions or
405 by code that needs to save and restore the error indicator temporarily, e.g.::
406
407 {
Serhiy Storchaka4398c122016-12-25 16:22:23 +0200408 PyObject *type, *value, *traceback;
Antoine Pitrou550ff722014-09-30 21:56:10 +0200409 PyErr_Fetch(&type, &value, &traceback);
410
411 /* ... code that might produce other errors ... */
412
413 PyErr_Restore(type, value, traceback);
414 }
415
416
417.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
418
419 Set the error indicator from the three objects. If the error indicator is
420 already set, it is cleared first. If the objects are *NULL*, the error
421 indicator is cleared. Do not pass a *NULL* type and non-*NULL* value or
422 traceback. The exception type should be a class. Do not pass an invalid
423 exception type or value. (Violating these rules will cause subtle problems
424 later.) This call takes away a reference to each object: you must own a
425 reference to each object before the call and after the call you no longer own
426 these references. (If you don't understand this, don't use this function. I
427 warned you.)
428
429 .. note::
430
431 This function is normally only used by code that needs to save and restore the
432 error indicator temporarily. Use :c:func:`PyErr_Fetch` to save the current
433 error indicator.
434
435
436.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
437
438 Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
439 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
440 not an instance of the same class. This function can be used to instantiate
441 the class in that case. If the values are already normalized, nothing happens.
442 The delayed normalization is implemented to improve performance.
443
444 .. note::
445
446 This function *does not* implicitly set the ``__traceback__``
447 attribute on the exception value. If setting the traceback
448 appropriately is desired, the following additional snippet is needed::
449
450 if (tb != NULL) {
451 PyException_SetTraceback(val, tb);
452 }
453
454
455.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
456
457 Retrieve the exception info, as known from ``sys.exc_info()``. This refers
458 to an exception that was *already caught*, not to an exception that was
459 freshly raised. Returns new references for the three objects, any of which
460 may be *NULL*. Does not modify the exception info state.
461
462 .. note::
463
464 This function is not normally used by code that wants to handle exceptions.
465 Rather, it can be used when code needs to save and restore the exception
466 state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the
467 exception state.
468
469 .. versionadded:: 3.3
470
471
472.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
473
474 Set the exception info, as known from ``sys.exc_info()``. This refers
475 to an exception that was *already caught*, not to an exception that was
476 freshly raised. This function steals the references of the arguments.
477 To clear the exception state, pass *NULL* for all three arguments.
478 For general rules about the three arguments, see :c:func:`PyErr_Restore`.
479
480 .. note::
481
482 This function is not normally used by code that wants to handle exceptions.
483 Rather, it can be used when code needs to save and restore the exception
484 state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception
485 state.
486
487 .. versionadded:: 3.3
488
489
490Signal Handling
491===============
492
493
Georg Brandl60203b42010-10-06 10:11:56 +0000494.. c:function:: int PyErr_CheckSignals()
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496 .. index::
497 module: signal
498 single: SIGINT
499 single: KeyboardInterrupt (built-in exception)
500
501 This function interacts with Python's signal handling. It checks whether a
502 signal has been sent to the processes and if so, invokes the corresponding
503 signal handler. If the :mod:`signal` module is supported, this can invoke a
504 signal handler written in Python. In all cases, the default effect for
505 :const:`SIGINT` is to raise the :exc:`KeyboardInterrupt` exception. If an
506 exception is raised the error indicator is set and the function returns ``-1``;
507 otherwise the function returns ``0``. The error indicator may or may not be
508 cleared if it was previously set.
509
510
Georg Brandl60203b42010-10-06 10:11:56 +0000511.. c:function:: void PyErr_SetInterrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513 .. index::
514 single: SIGINT
515 single: KeyboardInterrupt (built-in exception)
516
517 This function simulates the effect of a :const:`SIGINT` signal arriving --- the
Georg Brandl60203b42010-10-06 10:11:56 +0000518 next time :c:func:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will
Georg Brandl116aa622007-08-15 14:28:22 +0000519 be raised. It may be called without holding the interpreter lock.
520
521 .. % XXX This was described as obsolete, but is used in
Georg Brandl2067bfd2008-05-25 13:05:15 +0000522 .. % _thread.interrupt_main() (used from IDLE), so it's still needed.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524
Georg Brandl60203b42010-10-06 10:11:56 +0000525.. c:function:: int PySignal_SetWakeupFd(int fd)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000526
Victor Stinner11517102014-07-29 23:31:34 +0200527 This utility function specifies a file descriptor to which the signal number
528 is written as a single byte whenever a signal is received. *fd* must be
529 non-blocking. It returns the previous such file descriptor.
530
531 The value ``-1`` disables the feature; this is the initial state.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000532 This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
533 error checking. *fd* should be a valid file descriptor. The function should
534 only be called from the main thread.
535
Victor Stinner11517102014-07-29 23:31:34 +0200536 .. versionchanged:: 3.5
537 On Windows, the function now also supports socket handles.
538
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000539
Antoine Pitrou550ff722014-09-30 21:56:10 +0200540Exception Classes
541=================
542
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300543.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Georg Brandl325eb472011-07-13 15:59:24 +0200545 This utility function creates and returns a new exception class. The *name*
Georg Brandl116aa622007-08-15 14:28:22 +0000546 argument must be the name of the new exception, a C string of the form
Georg Brandl325eb472011-07-13 15:59:24 +0200547 ``module.classname``. The *base* and *dict* arguments are normally *NULL*.
548 This creates a class object derived from :exc:`Exception` (accessible in C as
Georg Brandl60203b42010-10-06 10:11:56 +0000549 :c:data:`PyExc_Exception`).
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551 The :attr:`__module__` attribute of the new class is set to the first part (up
552 to the last dot) of the *name* argument, and the class name is set to the last
553 part (after the last dot). The *base* argument can be used to specify alternate
554 base classes; it can either be only one class or a tuple of classes. The *dict*
555 argument can be used to specify a dictionary of class variables and methods.
556
557
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300558.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000559
Georg Brandl60203b42010-10-06 10:11:56 +0000560 Same as :c:func:`PyErr_NewException`, except that the new exception class can
Georg Brandl1e28a272009-12-28 08:41:01 +0000561 easily be given a docstring: If *doc* is non-*NULL*, it will be used as the
562 docstring for the exception class.
563
564 .. versionadded:: 3.2
565
566
Georg Brandlab6f2f62009-03-31 04:16:10 +0000567Exception Objects
568=================
569
Georg Brandl60203b42010-10-06 10:11:56 +0000570.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000571
572 Return the traceback associated with the exception as a new reference, as
573 accessible from Python through :attr:`__traceback__`. If there is no
574 traceback associated, this returns *NULL*.
575
576
Georg Brandl60203b42010-10-06 10:11:56 +0000577.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000578
579 Set the traceback associated with the exception to *tb*. Use ``Py_None`` to
580 clear it.
581
582
Georg Brandl60203b42010-10-06 10:11:56 +0000583.. c:function:: PyObject* PyException_GetContext(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000584
585 Return the context (another exception instance during whose handling *ex* was
586 raised) associated with the exception as a new reference, as accessible from
587 Python through :attr:`__context__`. If there is no context associated, this
588 returns *NULL*.
589
590
Georg Brandl60203b42010-10-06 10:11:56 +0000591.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000592
593 Set the context associated with the exception to *ctx*. Use *NULL* to clear
594 it. There is no type check to make sure that *ctx* is an exception instance.
595 This steals a reference to *ctx*.
596
597
Georg Brandl60203b42010-10-06 10:11:56 +0000598.. c:function:: PyObject* PyException_GetCause(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000599
Nick Coghlanab7bf212012-02-26 17:49:52 +1000600 Return the cause (either an exception instance, or :const:`None`,
601 set by ``raise ... from ...``) associated with the exception as a new
602 reference, as accessible from Python through :attr:`__cause__`.
603
Georg Brandlab6f2f62009-03-31 04:16:10 +0000604
Larry Hastings3732ed22014-03-15 21:13:56 -0700605.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000606
Larry Hastings3732ed22014-03-15 21:13:56 -0700607 Set the cause associated with the exception to *cause*. Use *NULL* to clear
608 it. There is no type check to make sure that *cause* is either an exception
609 instance or :const:`None`. This steals a reference to *cause*.
Nick Coghlanab7bf212012-02-26 17:49:52 +1000610
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700611 :attr:`__suppress_context__` is implicitly set to ``True`` by this function.
Georg Brandlab6f2f62009-03-31 04:16:10 +0000612
613
Georg Brandl5a932652010-11-23 07:54:19 +0000614.. _unicodeexceptions:
615
616Unicode Exception Objects
617=========================
618
619The following functions are used to create and modify Unicode exceptions from C.
620
621.. 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)
622
623 Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000624 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
625 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000626
627.. 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)
628
629 Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000630 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
631 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000632
633.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
634
635 Create a :class:`UnicodeTranslateError` object with the attributes *object*,
Martin Panter6245cb32016-04-15 02:14:19 +0000636 *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string.
Georg Brandl5a932652010-11-23 07:54:19 +0000637
638.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
639 PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
640
641 Return the *encoding* attribute of the given exception object.
642
643.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
644 PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
645 PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
646
647 Return the *object* attribute of the given exception object.
648
649.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
650 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
651 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
652
653 Get the *start* attribute of the given exception object and place it into
654 *\*start*. *start* must not be *NULL*. Return ``0`` on success, ``-1`` on
655 failure.
656
657.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
658 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
659 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
660
661 Set the *start* attribute of the given exception object to *start*. Return
662 ``0`` on success, ``-1`` on failure.
663
664.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
665 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
666 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
667
668 Get the *end* attribute of the given exception object and place it into
669 *\*end*. *end* must not be *NULL*. Return ``0`` on success, ``-1`` on
670 failure.
671
672.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
673 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
674 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
675
676 Set the *end* attribute of the given exception object to *end*. Return ``0``
677 on success, ``-1`` on failure.
678
679.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
680 PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
681 PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
682
683 Return the *reason* attribute of the given exception object.
684
685.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
686 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
687 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
688
689 Set the *reason* attribute of the given exception object to *reason*. Return
690 ``0`` on success, ``-1`` on failure.
691
692
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000693Recursion Control
694=================
695
696These two functions provide a way to perform safe recursive calls at the C
697level, both in the core and in extension modules. They are needed if the
698recursive code does not necessarily invoke Python code (which tracks its
699recursion depth automatically).
700
Serhiy Storchaka5fa22fc2015-06-21 16:26:28 +0300701.. c:function:: int Py_EnterRecursiveCall(const char *where)
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000702
703 Marks a point where a recursive C-level call is about to be performed.
704
Ezio Melottif1064492011-10-19 11:06:26 +0300705 If :const:`USE_STACKCHECK` is defined, this function checks if the OS
Georg Brandl60203b42010-10-06 10:11:56 +0000706 stack overflowed using :c:func:`PyOS_CheckStack`. In this is the case, it
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000707 sets a :exc:`MemoryError` and returns a nonzero value.
708
709 The function then checks if the recursion limit is reached. If this is the
Yury Selivanovf488fb42015-07-03 01:04:23 -0400710 case, a :exc:`RecursionError` is set and a nonzero value is returned.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000711 Otherwise, zero is returned.
712
713 *where* should be a string such as ``" in instance check"`` to be
Yury Selivanovf488fb42015-07-03 01:04:23 -0400714 concatenated to the :exc:`RecursionError` message caused by the recursion
715 depth limit.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000716
Georg Brandl60203b42010-10-06 10:11:56 +0000717.. c:function:: void Py_LeaveRecursiveCall()
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000718
Georg Brandl60203b42010-10-06 10:11:56 +0000719 Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each
720 *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000721
Antoine Pitrou39668f52013-08-01 21:12:45 +0200722Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000723special recursion handling. In addition to protecting the stack,
Antoine Pitrou39668f52013-08-01 21:12:45 +0200724:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000725following two functions facilitate this functionality. Effectively,
726these are the C equivalent to :func:`reprlib.recursive_repr`.
727
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000728.. c:function:: int Py_ReprEnter(PyObject *object)
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000729
Antoine Pitrou39668f52013-08-01 21:12:45 +0200730 Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000731 detect cycles.
732
733 If the object has already been processed, the function returns a
Antoine Pitrou39668f52013-08-01 21:12:45 +0200734 positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000735 should return a string object indicating a cycle. As examples,
736 :class:`dict` objects return ``{...}`` and :class:`list` objects
737 return ``[...]``.
738
739 The function will return a negative integer if the recursion limit
Antoine Pitrou39668f52013-08-01 21:12:45 +0200740 is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000741 typically return ``NULL``.
742
Antoine Pitrou39668f52013-08-01 21:12:45 +0200743 Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000744 implementation can continue normally.
745
746.. c:function:: void Py_ReprLeave(PyObject *object)
747
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000748 Ends a :c:func:`Py_ReprEnter`. Must be called once for each
749 invocation of :c:func:`Py_ReprEnter` that returns zero.
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000750
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000751
Georg Brandl116aa622007-08-15 14:28:22 +0000752.. _standardexceptions:
753
754Standard Exceptions
755===================
756
757All standard Python exceptions are available as global variables whose names are
758``PyExc_`` followed by the Python exception name. These have the type
Georg Brandl60203b42010-10-06 10:11:56 +0000759:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
Georg Brandl116aa622007-08-15 14:28:22 +0000760the variables:
761
cocoatomoe8c76312017-04-02 19:45:40 +0900762.. index::
763 single: PyExc_BaseException
764 single: PyExc_Exception
765 single: PyExc_ArithmeticError
766 single: PyExc_AssertionError
767 single: PyExc_AttributeError
768 single: PyExc_BlockingIOError
769 single: PyExc_BrokenPipeError
770 single: PyExc_BufferError
771 single: PyExc_ChildProcessError
772 single: PyExc_ConnectionAbortedError
773 single: PyExc_ConnectionError
774 single: PyExc_ConnectionRefusedError
775 single: PyExc_ConnectionResetError
776 single: PyExc_EOFError
777 single: PyExc_FileExistsError
778 single: PyExc_FileNotFoundError
779 single: PyExc_FloatingPointError
780 single: PyExc_GeneratorExit
781 single: PyExc_ImportError
782 single: PyExc_IndentationError
783 single: PyExc_IndexError
784 single: PyExc_InterruptedError
785 single: PyExc_IsADirectoryError
786 single: PyExc_KeyError
787 single: PyExc_KeyboardInterrupt
788 single: PyExc_LookupError
789 single: PyExc_MemoryError
790 single: PyExc_ModuleNotFoundError
791 single: PyExc_NameError
792 single: PyExc_NotADirectoryError
793 single: PyExc_NotImplementedError
794 single: PyExc_OSError
795 single: PyExc_OverflowError
796 single: PyExc_PermissionError
797 single: PyExc_ProcessLookupError
798 single: PyExc_RecursionError
799 single: PyExc_ReferenceError
800 single: PyExc_RuntimeError
801 single: PyExc_StopAsyncIteration
802 single: PyExc_StopIteration
803 single: PyExc_SyntaxError
804 single: PyExc_SystemError
805 single: PyExc_SystemExit
806 single: PyExc_TabError
Emily Morehouse8f59ee02019-01-24 16:49:56 -0700807 single: PyExc_TargetScopeError
cocoatomoe8c76312017-04-02 19:45:40 +0900808 single: PyExc_TimeoutError
809 single: PyExc_TypeError
810 single: PyExc_UnboundLocalError
811 single: PyExc_UnicodeDecodeError
812 single: PyExc_UnicodeEncodeError
813 single: PyExc_UnicodeError
814 single: PyExc_UnicodeTranslateError
815 single: PyExc_ValueError
816 single: PyExc_ZeroDivisionError
817
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200818+-----------------------------------------+---------------------------------+----------+
819| C Name | Python Name | Notes |
820+=========================================+=================================+==========+
821| :c:data:`PyExc_BaseException` | :exc:`BaseException` | \(1) |
822+-----------------------------------------+---------------------------------+----------+
823| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) |
824+-----------------------------------------+---------------------------------+----------+
825| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) |
826+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200827| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | |
828+-----------------------------------------+---------------------------------+----------+
829| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | |
830+-----------------------------------------+---------------------------------+----------+
831| :c:data:`PyExc_BlockingIOError` | :exc:`BlockingIOError` | |
832+-----------------------------------------+---------------------------------+----------+
833| :c:data:`PyExc_BrokenPipeError` | :exc:`BrokenPipeError` | |
834+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900835| :c:data:`PyExc_BufferError` | :exc:`BufferError` | |
836+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200837| :c:data:`PyExc_ChildProcessError` | :exc:`ChildProcessError` | |
838+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200839| :c:data:`PyExc_ConnectionAbortedError` | :exc:`ConnectionAbortedError` | |
840+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900841| :c:data:`PyExc_ConnectionError` | :exc:`ConnectionError` | |
842+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200843| :c:data:`PyExc_ConnectionRefusedError` | :exc:`ConnectionRefusedError` | |
844+-----------------------------------------+---------------------------------+----------+
845| :c:data:`PyExc_ConnectionResetError` | :exc:`ConnectionResetError` | |
846+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900847| :c:data:`PyExc_EOFError` | :exc:`EOFError` | |
848+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200849| :c:data:`PyExc_FileExistsError` | :exc:`FileExistsError` | |
850+-----------------------------------------+---------------------------------+----------+
851| :c:data:`PyExc_FileNotFoundError` | :exc:`FileNotFoundError` | |
852+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200853| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | |
854+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900855| :c:data:`PyExc_GeneratorExit` | :exc:`GeneratorExit` | |
856+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200857| :c:data:`PyExc_ImportError` | :exc:`ImportError` | |
858+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900859| :c:data:`PyExc_IndentationError` | :exc:`IndentationError` | |
Eric Snowc9432652016-09-07 15:42:32 -0700860+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200861| :c:data:`PyExc_IndexError` | :exc:`IndexError` | |
862+-----------------------------------------+---------------------------------+----------+
863| :c:data:`PyExc_InterruptedError` | :exc:`InterruptedError` | |
864+-----------------------------------------+---------------------------------+----------+
865| :c:data:`PyExc_IsADirectoryError` | :exc:`IsADirectoryError` | |
866+-----------------------------------------+---------------------------------+----------+
867| :c:data:`PyExc_KeyError` | :exc:`KeyError` | |
868+-----------------------------------------+---------------------------------+----------+
869| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | |
870+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900871| :c:data:`PyExc_LookupError` | :exc:`LookupError` | \(1) |
872+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200873| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | |
874+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900875| :c:data:`PyExc_ModuleNotFoundError` | :exc:`ModuleNotFoundError` | |
876+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200877| :c:data:`PyExc_NameError` | :exc:`NameError` | |
878+-----------------------------------------+---------------------------------+----------+
879| :c:data:`PyExc_NotADirectoryError` | :exc:`NotADirectoryError` | |
880+-----------------------------------------+---------------------------------+----------+
881| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | |
882+-----------------------------------------+---------------------------------+----------+
883| :c:data:`PyExc_OSError` | :exc:`OSError` | \(1) |
884+-----------------------------------------+---------------------------------+----------+
885| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | |
886+-----------------------------------------+---------------------------------+----------+
887| :c:data:`PyExc_PermissionError` | :exc:`PermissionError` | |
888+-----------------------------------------+---------------------------------+----------+
889| :c:data:`PyExc_ProcessLookupError` | :exc:`ProcessLookupError` | |
890+-----------------------------------------+---------------------------------+----------+
Yury Selivanovf488fb42015-07-03 01:04:23 -0400891| :c:data:`PyExc_RecursionError` | :exc:`RecursionError` | |
892+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200893| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) |
894+-----------------------------------------+---------------------------------+----------+
895| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | |
896+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900897| :c:data:`PyExc_StopAsyncIteration` | :exc:`StopAsyncIteration` | |
898+-----------------------------------------+---------------------------------+----------+
899| :c:data:`PyExc_StopIteration` | :exc:`StopIteration` | |
900+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200901| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | |
902+-----------------------------------------+---------------------------------+----------+
903| :c:data:`PyExc_SystemError` | :exc:`SystemError` | |
904+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200905| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | |
906+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900907| :c:data:`PyExc_TabError` | :exc:`TabError` | |
908+-----------------------------------------+---------------------------------+----------+
Emily Morehouse8f59ee02019-01-24 16:49:56 -0700909| :c:data:`PyExc_TargetScopeError` | :exc:`TargetScopeError` | |
910+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900911| :c:data:`PyExc_TimeoutError` | :exc:`TimeoutError` | |
912+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200913| :c:data:`PyExc_TypeError` | :exc:`TypeError` | |
914+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900915| :c:data:`PyExc_UnboundLocalError` | :exc:`UnboundLocalError` | |
916+-----------------------------------------+---------------------------------+----------+
917| :c:data:`PyExc_UnicodeDecodeError` | :exc:`UnicodeDecodeError` | |
918+-----------------------------------------+---------------------------------+----------+
919| :c:data:`PyExc_UnicodeEncodeError` | :exc:`UnicodeEncodeError` | |
920+-----------------------------------------+---------------------------------+----------+
921| :c:data:`PyExc_UnicodeError` | :exc:`UnicodeError` | |
922+-----------------------------------------+---------------------------------+----------+
923| :c:data:`PyExc_UnicodeTranslateError` | :exc:`UnicodeTranslateError` | |
924+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200925| :c:data:`PyExc_ValueError` | :exc:`ValueError` | |
926+-----------------------------------------+---------------------------------+----------+
927| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | |
928+-----------------------------------------+---------------------------------+----------+
929
930.. versionadded:: 3.3
931 :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
932 :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
933 :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
934 :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
935 :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
936 :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
937 :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
938 and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
939
Yury Selivanovf488fb42015-07-03 01:04:23 -0400940.. versionadded:: 3.5
cocoatomoe8c76312017-04-02 19:45:40 +0900941 :c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`.
Yury Selivanovf488fb42015-07-03 01:04:23 -0400942
cocoatomoe8c76312017-04-02 19:45:40 +0900943.. versionadded:: 3.6
944 :c:data:`PyExc_ModuleNotFoundError`.
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200945
946These are compatibility aliases to :c:data:`PyExc_OSError`:
947
cocoatomoe8c76312017-04-02 19:45:40 +0900948.. index::
949 single: PyExc_EnvironmentError
950 single: PyExc_IOError
951 single: PyExc_WindowsError
952
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200953+-------------------------------------+----------+
954| C Name | Notes |
955+=====================================+==========+
956| :c:data:`PyExc_EnvironmentError` | |
957+-------------------------------------+----------+
958| :c:data:`PyExc_IOError` | |
959+-------------------------------------+----------+
960| :c:data:`PyExc_WindowsError` | \(3) |
961+-------------------------------------+----------+
962
963.. versionchanged:: 3.3
964 These aliases used to be separate exception types.
965
Georg Brandl116aa622007-08-15 14:28:22 +0000966Notes:
967
968(1)
969 This is a base class for other standard exceptions.
970
971(2)
972 This is the same as :exc:`weakref.ReferenceError`.
973
974(3)
975 Only defined on Windows; protect code that uses this by testing that the
976 preprocessor macro ``MS_WINDOWS`` is defined.
cocoatomoe8c76312017-04-02 19:45:40 +0900977
delirious-lettuce3378b202017-05-19 14:37:57 -0600978.. _standardwarningcategories:
cocoatomoeaeda642017-04-15 11:06:02 +0900979
980Standard Warning Categories
981===========================
cocoatomoe8c76312017-04-02 19:45:40 +0900982
983All standard Python warning categories are available as global variables whose
984names are ``PyExc_`` followed by the Python exception name. These have the type
985:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
986the variables:
987
988.. index::
989 single: PyExc_Warning
990 single: PyExc_BytesWarning
delirious-lettuce3378b202017-05-19 14:37:57 -0600991 single: PyExc_DeprecationWarning
cocoatomoe8c76312017-04-02 19:45:40 +0900992 single: PyExc_FutureWarning
993 single: PyExc_ImportWarning
994 single: PyExc_PendingDeprecationWarning
995 single: PyExc_ResourceWarning
996 single: PyExc_RuntimeWarning
997 single: PyExc_SyntaxWarning
998 single: PyExc_UnicodeWarning
999 single: PyExc_UserWarning
1000
1001+------------------------------------------+---------------------------------+----------+
1002| C Name | Python Name | Notes |
1003+==========================================+=================================+==========+
1004| :c:data:`PyExc_Warning` | :exc:`Warning` | \(1) |
1005+------------------------------------------+---------------------------------+----------+
1006| :c:data:`PyExc_BytesWarning` | :exc:`BytesWarning` | |
1007+------------------------------------------+---------------------------------+----------+
1008| :c:data:`PyExc_DeprecationWarning` | :exc:`DeprecationWarning` | |
1009+------------------------------------------+---------------------------------+----------+
1010| :c:data:`PyExc_FutureWarning` | :exc:`FutureWarning` | |
1011+------------------------------------------+---------------------------------+----------+
1012| :c:data:`PyExc_ImportWarning` | :exc:`ImportWarning` | |
1013+------------------------------------------+---------------------------------+----------+
delirious-lettuce3378b202017-05-19 14:37:57 -06001014| :c:data:`PyExc_PendingDeprecationWarning`| :exc:`PendingDeprecationWarning`| |
cocoatomoe8c76312017-04-02 19:45:40 +09001015+------------------------------------------+---------------------------------+----------+
1016| :c:data:`PyExc_ResourceWarning` | :exc:`ResourceWarning` | |
1017+------------------------------------------+---------------------------------+----------+
1018| :c:data:`PyExc_RuntimeWarning` | :exc:`RuntimeWarning` | |
1019+------------------------------------------+---------------------------------+----------+
1020| :c:data:`PyExc_SyntaxWarning` | :exc:`SyntaxWarning` | |
1021+------------------------------------------+---------------------------------+----------+
1022| :c:data:`PyExc_UnicodeWarning` | :exc:`UnicodeWarning` | |
1023+------------------------------------------+---------------------------------+----------+
1024| :c:data:`PyExc_UserWarning` | :exc:`UserWarning` | |
1025+------------------------------------------+---------------------------------+----------+
1026
1027.. versionadded:: 3.2
1028 :c:data:`PyExc_ResourceWarning`.
1029
1030Notes:
1031
1032(1)
1033 This is a base class for other standard warning categories.