blob: 79e6f97a44c7d88a385bf48a42953429216add63 [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.
Miss Islington (bot)661151b2019-02-27 15:45:28 -080056 **Unless** the error is a ``SystemExit``. In that case the no traceback
57 is printed and Python process will exit with the error code specified by
58 the ``SystemExit`` instance.
59
60 Call this function **only** when the error indicator is set. Otherwise it
61 will cause a fatal error!
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
Victor Stinnera58db962019-05-22 18:23:28 +020084 An exception must be set when calling this function.
85
Georg Brandl116aa622007-08-15 14:28:22 +000086
Antoine Pitrou550ff722014-09-30 21:56:10 +020087Raising exceptions
88==================
Georg Brandl116aa622007-08-15 14:28:22 +000089
Antoine Pitrou550ff722014-09-30 21:56:10 +020090These functions help you set the current thread's error indicator.
91For convenience, some of these functions will always return a
92NULL pointer for use in a ``return`` statement.
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020093
94
Georg Brandl60203b42010-10-06 10:11:56 +000095.. c:function:: void PyErr_SetString(PyObject *type, const char *message)
Georg Brandl116aa622007-08-15 14:28:22 +000096
97 This is the most common way to set the error indicator. The first argument
98 specifies the exception type; it is normally one of the standard exceptions,
Georg Brandl60203b42010-10-06 10:11:56 +000099 e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count.
Victor Stinner257d38f2010-10-09 10:12:11 +0000100 The second argument is an error message; it is decoded from ``'utf-8``'.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102
Georg Brandl60203b42010-10-06 10:11:56 +0000103.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Georg Brandl60203b42010-10-06 10:11:56 +0000105 This function is similar to :c:func:`PyErr_SetString` but lets you specify an
Georg Brandl116aa622007-08-15 14:28:22 +0000106 arbitrary Python object for the "value" of the exception.
107
108
Georg Brandl60203b42010-10-06 10:11:56 +0000109.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Antoine Pitroua66e0292010-11-27 20:40:43 +0000111 This function sets the error indicator and returns *NULL*. *exception*
112 should be a Python exception class. The *format* and subsequent
113 parameters help format the error message; they have the same meaning and
Victor Stinnerb1dbd102010-12-28 11:02:46 +0000114 values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
Victor Stinner555a24f2010-12-27 01:49:26 +0000115 string.
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000116
Georg Brandl116aa622007-08-15 14:28:22 +0000117
Antoine Pitrou0676a402014-09-30 21:16:27 +0200118.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
119
Georg Brandl93a56cd2014-10-30 22:25:41 +0100120 Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather
Antoine Pitrou0676a402014-09-30 21:16:27 +0200121 than a variable number of arguments.
122
123 .. versionadded:: 3.5
124
125
Georg Brandl60203b42010-10-06 10:11:56 +0000126.. c:function:: void PyErr_SetNone(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128 This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
129
130
Georg Brandl60203b42010-10-06 10:11:56 +0000131.. c:function:: int PyErr_BadArgument()
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
134 *message* indicates that a built-in operation was invoked with an illegal
135 argument. It is mostly for internal use.
136
137
Georg Brandl60203b42010-10-06 10:11:56 +0000138.. c:function:: PyObject* PyErr_NoMemory()
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140 This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL*
141 so an object allocation function can write ``return PyErr_NoMemory();`` when it
142 runs out of memory.
143
144
Georg Brandl60203b42010-10-06 10:11:56 +0000145.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147 .. index:: single: strerror()
148
149 This is a convenience function to raise an exception when a C library function
Georg Brandl60203b42010-10-06 10:11:56 +0000150 has returned an error and set the C variable :c:data:`errno`. It constructs a
151 tuple object whose first item is the integer :c:data:`errno` value and whose
152 second item is the corresponding error message (gotten from :c:func:`strerror`),
Georg Brandl116aa622007-08-15 14:28:22 +0000153 and then calls ``PyErr_SetObject(type, object)``. On Unix, when the
Georg Brandl60203b42010-10-06 10:11:56 +0000154 :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call,
155 this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator,
Georg Brandl116aa622007-08-15 14:28:22 +0000156 leaves it set to that. The function always returns *NULL*, so a wrapper
157 function around a system call can write ``return PyErr_SetFromErrno(type);``
158 when the system call returns an error.
159
160
Georg Brandl991fc572013-04-14 11:12:16 +0200161.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Georg Brandl60203b42010-10-06 10:11:56 +0000163 Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
Georg Brandl991fc572013-04-14 11:12:16 +0200164 *filenameObject* is not *NULL*, it is passed to the constructor of *type* as
Andrew Svetlov08af0002014-04-01 01:13:30 +0300165 a third parameter. In the case of :exc:`OSError` exception,
166 this is used to define the :attr:`filename` attribute of the
Georg Brandl991fc572013-04-14 11:12:16 +0200167 exception instance.
168
169
Larry Hastingsb0827312014-02-09 22:05:19 -0800170.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
171
172 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but takes a second
173 filename object, for raising errors when a function that takes two filenames
174 fails.
175
Georg Brandldf48b972014-03-24 09:06:18 +0100176 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800177
178
Georg Brandl991fc572013-04-14 11:12:16 +0200179.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
180
181 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename
182 is given as a C string. *filename* is decoded from the filesystem encoding
Victor Stinner14e461d2013-08-26 22:28:21 +0200183 (:func:`os.fsdecode`).
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185
Georg Brandl60203b42010-10-06 10:11:56 +0000186.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188 This is a convenience function to raise :exc:`WindowsError`. If called with
Georg Brandl60203b42010-10-06 10:11:56 +0000189 *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError`
190 is used instead. It calls the Win32 function :c:func:`FormatMessage` to retrieve
191 the Windows description of error code given by *ierr* or :c:func:`GetLastError`,
Georg Brandl116aa622007-08-15 14:28:22 +0000192 then it constructs a tuple object whose first item is the *ierr* value and whose
193 second item is the corresponding error message (gotten from
Georg Brandl60203b42010-10-06 10:11:56 +0000194 :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400195 object)``. This function always returns *NULL*.
196
197 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
Georg Brandl60203b42010-10-06 10:11:56 +0000200.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Georg Brandl60203b42010-10-06 10:11:56 +0000202 Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400203 specifying the exception type to be raised.
204
205 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Georg Brandl60203b42010-10-06 10:11:56 +0000208.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Georg Brandl991fc572013-04-14 11:12:16 +0200210 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
211 filename is given as a C string. *filename* is decoded from the filesystem
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400212 encoding (:func:`os.fsdecode`).
213
214 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216
Georg Brandl991fc572013-04-14 11:12:16 +0200217.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)
218
219 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, with an
220 additional parameter specifying the exception type to be raised.
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400221
222 .. availability:: Windows.
Georg Brandl991fc572013-04-14 11:12:16 +0200223
224
Larry Hastingsb0827312014-02-09 22:05:19 -0800225.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
226
227 Similar to :c:func:`PyErr_SetExcFromWindowsErrWithFilenameObject`,
228 but accepts a second filename object.
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400229
230 .. availability:: Windows.
Larry Hastingsb0827312014-02-09 22:05:19 -0800231
Georg Brandldf48b972014-03-24 09:06:18 +0100232 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800233
234
Georg Brandl991fc572013-04-14 11:12:16 +0200235.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Georg Brandl60203b42010-10-06 10:11:56 +0000237 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400238 parameter specifying the exception type to be raised.
239
240 .. availability:: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Georg Brandlf4095832012-04-24 19:16:24 +0200242
Brian Curtin09b86d12012-04-17 16:57:09 -0500243.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brian Curtinbd439742012-04-16 15:14:36 -0500244
245 This is a convenience function to raise :exc:`ImportError`. *msg* will be
Brian Curtin09b86d12012-04-17 16:57:09 -0500246 set as the exception's message string. *name* and *path*, both of which can
247 be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name``
248 and ``path`` attributes.
Brian Curtinbd439742012-04-16 15:14:36 -0500249
Brian Curtinbded8942012-04-16 18:14:09 -0500250 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Georg Brandlf4095832012-04-24 19:16:24 +0200252
Victor Stinner14e461d2013-08-26 22:28:21 +0200253.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000254
255 Set file, line, and offset information for the current exception. If the
256 current exception is not a :exc:`SyntaxError`, then it sets additional
257 attributes, which make the exception printing subsystem think the exception
Victor Stinner14e461d2013-08-26 22:28:21 +0200258 is a :exc:`SyntaxError`.
Benjamin Peterson2c539712010-09-20 22:42:10 +0000259
Georg Brandldf48b972014-03-24 09:06:18 +0100260 .. versionadded:: 3.4
Victor Stinner14e461d2013-08-26 22:28:21 +0200261
262
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300263.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Victor Stinner14e461d2013-08-26 22:28:21 +0200264
265 Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
266 decoded from the filesystem encoding (:func:`os.fsdecode`).
267
Georg Brandldf48b972014-03-24 09:06:18 +0100268 .. versionadded:: 3.2
Benjamin Petersonb5d23b42010-09-21 21:29:26 +0000269
Benjamin Peterson2c539712010-09-20 22:42:10 +0000270
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300271.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000272
Victor Stinner14e461d2013-08-26 22:28:21 +0200273 Like :c:func:`PyErr_SyntaxLocationEx`, but the col_offset parameter is
Benjamin Peterson2c539712010-09-20 22:42:10 +0000274 omitted.
275
276
Georg Brandl60203b42010-10-06 10:11:56 +0000277.. c:function:: void PyErr_BadInternalCall()
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000279 This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
280 where *message* indicates that an internal operation (e.g. a Python/C API
281 function) was invoked with an illegal argument. It is mostly for internal
282 use.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284
Antoine Pitrou550ff722014-09-30 21:56:10 +0200285Issuing warnings
286================
287
288Use these functions to issue warnings from C code. They mirror similar
289functions exported by the Python :mod:`warnings` module. They normally
290print a warning message to *sys.stderr*; however, it is
291also possible that the user has specified that warnings are to be turned into
292errors, and in that case they will raise an exception. It is also possible that
293the functions raise an exception because of a problem with the warning machinery.
294The return value is ``0`` if no exception is raised, or ``-1`` if an exception
295is raised. (It is not possible to determine whether a warning message is
296actually printed, nor what the reason is for the exception; this is
297intentional.) If an exception is raised, the caller should do its normal
298exception handling (for example, :c:func:`Py_DECREF` owned references and return
299an error value).
300
Georg Brandl97435162014-10-06 12:58:00 +0200301.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303 Issue a warning message. The *category* argument is a warning category (see
Martin Panter6245cb32016-04-15 02:14:19 +0000304 below) or *NULL*; the *message* argument is a UTF-8 encoded string. *stack_level* is a
Georg Brandl116aa622007-08-15 14:28:22 +0000305 positive number giving a number of stack frames; the warning will be issued from
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000306 the currently executing line of code in that stack frame. A *stack_level* of 1
Georg Brandl60203b42010-10-06 10:11:56 +0000307 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that,
Georg Brandl116aa622007-08-15 14:28:22 +0000308 and so forth.
309
cocoatomoeaeda642017-04-15 11:06:02 +0900310 Warning categories must be subclasses of :c:data:`PyExc_Warning`;
311 :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`;
312 the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard
313 Python warning categories are available as global variables whose names are
delirious-lettuce3378b202017-05-19 14:37:57 -0600314 enumerated at :ref:`standardwarningcategories`.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316 For information about warning control, see the documentation for the
317 :mod:`warnings` module and the :option:`-W` option in the command line
318 documentation. There is no C API for warning control.
319
Eric Snow46f97b82016-09-07 16:56:15 -0700320.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *msg, PyObject *name, PyObject *path)
321
322 Much like :c:func:`PyErr_SetImportError` but this function allows for
323 specifying a subclass of :exc:`ImportError` to raise.
324
Yury Selivanov3479b5f2016-11-10 13:25:26 -0500325 .. versionadded:: 3.6
Eric Snow46f97b82016-09-07 16:56:15 -0700326
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Victor Stinner14e461d2013-08-26 22:28:21 +0200328.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330 Issue a warning message with explicit control over all warning attributes. This
331 is a straightforward wrapper around the Python function
332 :func:`warnings.warn_explicit`, see there for more information. The *module*
333 and *registry* arguments may be set to *NULL* to get the default effect
Victor Stinner14e461d2013-08-26 22:28:21 +0200334 described there.
335
336 .. versionadded:: 3.4
337
338
339.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
340
341 Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and
342 *module* are UTF-8 encoded strings, and *filename* is decoded from the
343 filesystem encoding (:func:`os.fsdecode`).
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345
Georg Brandl60203b42010-10-06 10:11:56 +0000346.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000347
Georg Brandl60203b42010-10-06 10:11:56 +0000348 Function similar to :c:func:`PyErr_WarnEx`, but use
Victor Stinner555a24f2010-12-27 01:49:26 +0000349 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
350 an ASCII-encoded string.
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000351
352 .. versionadded:: 3.2
353
Georg Brandlf4095832012-04-24 19:16:24 +0200354
Victor Stinner914cde82016-03-19 01:03:51 +0100355.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
356
357 Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
358 :exc:`ResourceWarning` and pass *source* to :func:`warnings.WarningMessage`.
359
360 .. versionadded:: 3.6
361
362
Antoine Pitrou550ff722014-09-30 21:56:10 +0200363Querying the error indicator
364============================
365
366.. c:function:: PyObject* PyErr_Occurred()
367
368 Test whether the error indicator is set. If set, return the exception *type*
369 (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
370 functions or to :c:func:`PyErr_Restore`). If not set, return *NULL*. You do not
371 own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
372 it.
373
374 .. note::
375
376 Do not compare the return value to a specific exception; use
377 :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could
378 easily fail since the exception may be an instance instead of a class, in the
Benjamin Peterson610bc6a2015-01-13 09:20:31 -0500379 case of a class exception, or it may be a subclass of the expected exception.)
Antoine Pitrou550ff722014-09-30 21:56:10 +0200380
381
382.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
383
384 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This
385 should only be called when an exception is actually set; a memory access
386 violation will occur if no exception has been raised.
387
388
389.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
390
391 Return true if the *given* exception matches the exception type in *exc*. If
392 *exc* is a class object, this also returns true when *given* is an instance
393 of a subclass. If *exc* is a tuple, all exception types in the tuple (and
394 recursively in subtuples) are searched for a match.
395
396
397.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
398
399 Retrieve the error indicator into three variables whose addresses are passed.
400 If the error indicator is not set, set all three variables to *NULL*. If it is
401 set, it will be cleared and you own a reference to each object retrieved. The
402 value and traceback object may be *NULL* even when the type object is not.
403
404 .. note::
405
406 This function is normally only used by code that needs to catch exceptions or
407 by code that needs to save and restore the error indicator temporarily, e.g.::
408
409 {
Serhiy Storchaka4398c122016-12-25 16:22:23 +0200410 PyObject *type, *value, *traceback;
Antoine Pitrou550ff722014-09-30 21:56:10 +0200411 PyErr_Fetch(&type, &value, &traceback);
412
413 /* ... code that might produce other errors ... */
414
415 PyErr_Restore(type, value, traceback);
416 }
417
418
419.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
420
421 Set the error indicator from the three objects. If the error indicator is
422 already set, it is cleared first. If the objects are *NULL*, the error
423 indicator is cleared. Do not pass a *NULL* type and non-*NULL* value or
424 traceback. The exception type should be a class. Do not pass an invalid
425 exception type or value. (Violating these rules will cause subtle problems
426 later.) This call takes away a reference to each object: you must own a
427 reference to each object before the call and after the call you no longer own
428 these references. (If you don't understand this, don't use this function. I
429 warned you.)
430
431 .. note::
432
433 This function is normally only used by code that needs to save and restore the
434 error indicator temporarily. Use :c:func:`PyErr_Fetch` to save the current
435 error indicator.
436
437
438.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
439
440 Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
441 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
442 not an instance of the same class. This function can be used to instantiate
443 the class in that case. If the values are already normalized, nothing happens.
444 The delayed normalization is implemented to improve performance.
445
446 .. note::
447
448 This function *does not* implicitly set the ``__traceback__``
449 attribute on the exception value. If setting the traceback
450 appropriately is desired, the following additional snippet is needed::
451
452 if (tb != NULL) {
453 PyException_SetTraceback(val, tb);
454 }
455
456
457.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
458
459 Retrieve the exception info, as known from ``sys.exc_info()``. This refers
460 to an exception that was *already caught*, not to an exception that was
461 freshly raised. Returns new references for the three objects, any of which
462 may be *NULL*. Does not modify the exception info state.
463
464 .. note::
465
466 This function is not normally used by code that wants to handle exceptions.
467 Rather, it can be used when code needs to save and restore the exception
468 state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the
469 exception state.
470
471 .. versionadded:: 3.3
472
473
474.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
475
476 Set the exception info, as known from ``sys.exc_info()``. This refers
477 to an exception that was *already caught*, not to an exception that was
478 freshly raised. This function steals the references of the arguments.
479 To clear the exception state, pass *NULL* for all three arguments.
480 For general rules about the three arguments, see :c:func:`PyErr_Restore`.
481
482 .. note::
483
484 This function is not normally used by code that wants to handle exceptions.
485 Rather, it can be used when code needs to save and restore the exception
486 state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception
487 state.
488
489 .. versionadded:: 3.3
490
491
492Signal Handling
493===============
494
495
Georg Brandl60203b42010-10-06 10:11:56 +0000496.. c:function:: int PyErr_CheckSignals()
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498 .. index::
499 module: signal
500 single: SIGINT
501 single: KeyboardInterrupt (built-in exception)
502
503 This function interacts with Python's signal handling. It checks whether a
504 signal has been sent to the processes and if so, invokes the corresponding
505 signal handler. If the :mod:`signal` module is supported, this can invoke a
506 signal handler written in Python. In all cases, the default effect for
507 :const:`SIGINT` is to raise the :exc:`KeyboardInterrupt` exception. If an
508 exception is raised the error indicator is set and the function returns ``-1``;
509 otherwise the function returns ``0``. The error indicator may or may not be
510 cleared if it was previously set.
511
512
Georg Brandl60203b42010-10-06 10:11:56 +0000513.. c:function:: void PyErr_SetInterrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515 .. index::
516 single: SIGINT
517 single: KeyboardInterrupt (built-in exception)
518
519 This function simulates the effect of a :const:`SIGINT` signal arriving --- the
Georg Brandl60203b42010-10-06 10:11:56 +0000520 next time :c:func:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will
Georg Brandl116aa622007-08-15 14:28:22 +0000521 be raised. It may be called without holding the interpreter lock.
522
523 .. % XXX This was described as obsolete, but is used in
Georg Brandl2067bfd2008-05-25 13:05:15 +0000524 .. % _thread.interrupt_main() (used from IDLE), so it's still needed.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
Georg Brandl60203b42010-10-06 10:11:56 +0000527.. c:function:: int PySignal_SetWakeupFd(int fd)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000528
Victor Stinner11517102014-07-29 23:31:34 +0200529 This utility function specifies a file descriptor to which the signal number
530 is written as a single byte whenever a signal is received. *fd* must be
531 non-blocking. It returns the previous such file descriptor.
532
533 The value ``-1`` disables the feature; this is the initial state.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000534 This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
535 error checking. *fd* should be a valid file descriptor. The function should
536 only be called from the main thread.
537
Victor Stinner11517102014-07-29 23:31:34 +0200538 .. versionchanged:: 3.5
539 On Windows, the function now also supports socket handles.
540
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000541
Antoine Pitrou550ff722014-09-30 21:56:10 +0200542Exception Classes
543=================
544
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300545.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Georg Brandl325eb472011-07-13 15:59:24 +0200547 This utility function creates and returns a new exception class. The *name*
Georg Brandl116aa622007-08-15 14:28:22 +0000548 argument must be the name of the new exception, a C string of the form
Georg Brandl325eb472011-07-13 15:59:24 +0200549 ``module.classname``. The *base* and *dict* arguments are normally *NULL*.
550 This creates a class object derived from :exc:`Exception` (accessible in C as
Georg Brandl60203b42010-10-06 10:11:56 +0000551 :c:data:`PyExc_Exception`).
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553 The :attr:`__module__` attribute of the new class is set to the first part (up
554 to the last dot) of the *name* argument, and the class name is set to the last
555 part (after the last dot). The *base* argument can be used to specify alternate
556 base classes; it can either be only one class or a tuple of classes. The *dict*
557 argument can be used to specify a dictionary of class variables and methods.
558
559
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300560.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000561
Georg Brandl60203b42010-10-06 10:11:56 +0000562 Same as :c:func:`PyErr_NewException`, except that the new exception class can
Georg Brandl1e28a272009-12-28 08:41:01 +0000563 easily be given a docstring: If *doc* is non-*NULL*, it will be used as the
564 docstring for the exception class.
565
566 .. versionadded:: 3.2
567
568
Georg Brandlab6f2f62009-03-31 04:16:10 +0000569Exception Objects
570=================
571
Georg Brandl60203b42010-10-06 10:11:56 +0000572.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000573
574 Return the traceback associated with the exception as a new reference, as
575 accessible from Python through :attr:`__traceback__`. If there is no
576 traceback associated, this returns *NULL*.
577
578
Georg Brandl60203b42010-10-06 10:11:56 +0000579.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000580
581 Set the traceback associated with the exception to *tb*. Use ``Py_None`` to
582 clear it.
583
584
Georg Brandl60203b42010-10-06 10:11:56 +0000585.. c:function:: PyObject* PyException_GetContext(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000586
587 Return the context (another exception instance during whose handling *ex* was
588 raised) associated with the exception as a new reference, as accessible from
589 Python through :attr:`__context__`. If there is no context associated, this
590 returns *NULL*.
591
592
Georg Brandl60203b42010-10-06 10:11:56 +0000593.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000594
595 Set the context associated with the exception to *ctx*. Use *NULL* to clear
596 it. There is no type check to make sure that *ctx* is an exception instance.
597 This steals a reference to *ctx*.
598
599
Georg Brandl60203b42010-10-06 10:11:56 +0000600.. c:function:: PyObject* PyException_GetCause(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000601
Nick Coghlanab7bf212012-02-26 17:49:52 +1000602 Return the cause (either an exception instance, or :const:`None`,
603 set by ``raise ... from ...``) associated with the exception as a new
604 reference, as accessible from Python through :attr:`__cause__`.
605
Georg Brandlab6f2f62009-03-31 04:16:10 +0000606
Larry Hastings3732ed22014-03-15 21:13:56 -0700607.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000608
Larry Hastings3732ed22014-03-15 21:13:56 -0700609 Set the cause associated with the exception to *cause*. Use *NULL* to clear
610 it. There is no type check to make sure that *cause* is either an exception
611 instance or :const:`None`. This steals a reference to *cause*.
Nick Coghlanab7bf212012-02-26 17:49:52 +1000612
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700613 :attr:`__suppress_context__` is implicitly set to ``True`` by this function.
Georg Brandlab6f2f62009-03-31 04:16:10 +0000614
615
Georg Brandl5a932652010-11-23 07:54:19 +0000616.. _unicodeexceptions:
617
618Unicode Exception Objects
619=========================
620
621The following functions are used to create and modify Unicode exceptions from C.
622
623.. 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)
624
625 Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000626 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
627 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000628
629.. 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)
630
631 Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000632 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
633 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000634
635.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
636
637 Create a :class:`UnicodeTranslateError` object with the attributes *object*,
Martin Panter6245cb32016-04-15 02:14:19 +0000638 *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string.
Georg Brandl5a932652010-11-23 07:54:19 +0000639
640.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
641 PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
642
643 Return the *encoding* attribute of the given exception object.
644
645.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
646 PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
647 PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
648
649 Return the *object* attribute of the given exception object.
650
651.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
652 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
653 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
654
655 Get the *start* attribute of the given exception object and place it into
656 *\*start*. *start* must not be *NULL*. Return ``0`` on success, ``-1`` on
657 failure.
658
659.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
660 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
661 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
662
663 Set the *start* attribute of the given exception object to *start*. Return
664 ``0`` on success, ``-1`` on failure.
665
666.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
667 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
668 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
669
670 Get the *end* attribute of the given exception object and place it into
671 *\*end*. *end* must not be *NULL*. Return ``0`` on success, ``-1`` on
672 failure.
673
674.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
675 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
676 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
677
678 Set the *end* attribute of the given exception object to *end*. Return ``0``
679 on success, ``-1`` on failure.
680
681.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
682 PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
683 PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
684
685 Return the *reason* attribute of the given exception object.
686
687.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
688 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
689 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
690
691 Set the *reason* attribute of the given exception object to *reason*. Return
692 ``0`` on success, ``-1`` on failure.
693
694
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000695Recursion Control
696=================
697
698These two functions provide a way to perform safe recursive calls at the C
699level, both in the core and in extension modules. They are needed if the
700recursive code does not necessarily invoke Python code (which tracks its
701recursion depth automatically).
702
Serhiy Storchaka5fa22fc2015-06-21 16:26:28 +0300703.. c:function:: int Py_EnterRecursiveCall(const char *where)
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000704
705 Marks a point where a recursive C-level call is about to be performed.
706
Ezio Melottif1064492011-10-19 11:06:26 +0300707 If :const:`USE_STACKCHECK` is defined, this function checks if the OS
Georg Brandl60203b42010-10-06 10:11:56 +0000708 stack overflowed using :c:func:`PyOS_CheckStack`. In this is the case, it
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000709 sets a :exc:`MemoryError` and returns a nonzero value.
710
711 The function then checks if the recursion limit is reached. If this is the
Yury Selivanovf488fb42015-07-03 01:04:23 -0400712 case, a :exc:`RecursionError` is set and a nonzero value is returned.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000713 Otherwise, zero is returned.
714
715 *where* should be a string such as ``" in instance check"`` to be
Yury Selivanovf488fb42015-07-03 01:04:23 -0400716 concatenated to the :exc:`RecursionError` message caused by the recursion
717 depth limit.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000718
Georg Brandl60203b42010-10-06 10:11:56 +0000719.. c:function:: void Py_LeaveRecursiveCall()
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000720
Georg Brandl60203b42010-10-06 10:11:56 +0000721 Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each
722 *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000723
Antoine Pitrou39668f52013-08-01 21:12:45 +0200724Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000725special recursion handling. In addition to protecting the stack,
Antoine Pitrou39668f52013-08-01 21:12:45 +0200726:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000727following two functions facilitate this functionality. Effectively,
728these are the C equivalent to :func:`reprlib.recursive_repr`.
729
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000730.. c:function:: int Py_ReprEnter(PyObject *object)
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000731
Antoine Pitrou39668f52013-08-01 21:12:45 +0200732 Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000733 detect cycles.
734
735 If the object has already been processed, the function returns a
Antoine Pitrou39668f52013-08-01 21:12:45 +0200736 positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000737 should return a string object indicating a cycle. As examples,
738 :class:`dict` objects return ``{...}`` and :class:`list` objects
739 return ``[...]``.
740
741 The function will return a negative integer if the recursion limit
Antoine Pitrou39668f52013-08-01 21:12:45 +0200742 is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000743 typically return ``NULL``.
744
Antoine Pitrou39668f52013-08-01 21:12:45 +0200745 Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000746 implementation can continue normally.
747
748.. c:function:: void Py_ReprLeave(PyObject *object)
749
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000750 Ends a :c:func:`Py_ReprEnter`. Must be called once for each
751 invocation of :c:func:`Py_ReprEnter` that returns zero.
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000752
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000753
Georg Brandl116aa622007-08-15 14:28:22 +0000754.. _standardexceptions:
755
756Standard Exceptions
757===================
758
759All standard Python exceptions are available as global variables whose names are
760``PyExc_`` followed by the Python exception name. These have the type
Georg Brandl60203b42010-10-06 10:11:56 +0000761:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
Georg Brandl116aa622007-08-15 14:28:22 +0000762the variables:
763
cocoatomoe8c76312017-04-02 19:45:40 +0900764.. index::
765 single: PyExc_BaseException
766 single: PyExc_Exception
767 single: PyExc_ArithmeticError
768 single: PyExc_AssertionError
769 single: PyExc_AttributeError
770 single: PyExc_BlockingIOError
771 single: PyExc_BrokenPipeError
772 single: PyExc_BufferError
773 single: PyExc_ChildProcessError
774 single: PyExc_ConnectionAbortedError
775 single: PyExc_ConnectionError
776 single: PyExc_ConnectionRefusedError
777 single: PyExc_ConnectionResetError
778 single: PyExc_EOFError
779 single: PyExc_FileExistsError
780 single: PyExc_FileNotFoundError
781 single: PyExc_FloatingPointError
782 single: PyExc_GeneratorExit
783 single: PyExc_ImportError
784 single: PyExc_IndentationError
785 single: PyExc_IndexError
786 single: PyExc_InterruptedError
787 single: PyExc_IsADirectoryError
788 single: PyExc_KeyError
789 single: PyExc_KeyboardInterrupt
790 single: PyExc_LookupError
791 single: PyExc_MemoryError
792 single: PyExc_ModuleNotFoundError
793 single: PyExc_NameError
794 single: PyExc_NotADirectoryError
795 single: PyExc_NotImplementedError
796 single: PyExc_OSError
797 single: PyExc_OverflowError
798 single: PyExc_PermissionError
799 single: PyExc_ProcessLookupError
800 single: PyExc_RecursionError
801 single: PyExc_ReferenceError
802 single: PyExc_RuntimeError
803 single: PyExc_StopAsyncIteration
804 single: PyExc_StopIteration
805 single: PyExc_SyntaxError
806 single: PyExc_SystemError
807 single: PyExc_SystemExit
808 single: PyExc_TabError
809 single: PyExc_TimeoutError
810 single: PyExc_TypeError
811 single: PyExc_UnboundLocalError
812 single: PyExc_UnicodeDecodeError
813 single: PyExc_UnicodeEncodeError
814 single: PyExc_UnicodeError
815 single: PyExc_UnicodeTranslateError
816 single: PyExc_ValueError
817 single: PyExc_ZeroDivisionError
818
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200819+-----------------------------------------+---------------------------------+----------+
820| C Name | Python Name | Notes |
821+=========================================+=================================+==========+
822| :c:data:`PyExc_BaseException` | :exc:`BaseException` | \(1) |
823+-----------------------------------------+---------------------------------+----------+
824| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) |
825+-----------------------------------------+---------------------------------+----------+
826| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) |
827+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200828| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | |
829+-----------------------------------------+---------------------------------+----------+
830| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | |
831+-----------------------------------------+---------------------------------+----------+
832| :c:data:`PyExc_BlockingIOError` | :exc:`BlockingIOError` | |
833+-----------------------------------------+---------------------------------+----------+
834| :c:data:`PyExc_BrokenPipeError` | :exc:`BrokenPipeError` | |
835+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900836| :c:data:`PyExc_BufferError` | :exc:`BufferError` | |
837+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200838| :c:data:`PyExc_ChildProcessError` | :exc:`ChildProcessError` | |
839+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200840| :c:data:`PyExc_ConnectionAbortedError` | :exc:`ConnectionAbortedError` | |
841+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900842| :c:data:`PyExc_ConnectionError` | :exc:`ConnectionError` | |
843+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200844| :c:data:`PyExc_ConnectionRefusedError` | :exc:`ConnectionRefusedError` | |
845+-----------------------------------------+---------------------------------+----------+
846| :c:data:`PyExc_ConnectionResetError` | :exc:`ConnectionResetError` | |
847+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900848| :c:data:`PyExc_EOFError` | :exc:`EOFError` | |
849+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200850| :c:data:`PyExc_FileExistsError` | :exc:`FileExistsError` | |
851+-----------------------------------------+---------------------------------+----------+
852| :c:data:`PyExc_FileNotFoundError` | :exc:`FileNotFoundError` | |
853+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200854| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | |
855+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900856| :c:data:`PyExc_GeneratorExit` | :exc:`GeneratorExit` | |
857+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200858| :c:data:`PyExc_ImportError` | :exc:`ImportError` | |
859+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900860| :c:data:`PyExc_IndentationError` | :exc:`IndentationError` | |
Eric Snowc9432652016-09-07 15:42:32 -0700861+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200862| :c:data:`PyExc_IndexError` | :exc:`IndexError` | |
863+-----------------------------------------+---------------------------------+----------+
864| :c:data:`PyExc_InterruptedError` | :exc:`InterruptedError` | |
865+-----------------------------------------+---------------------------------+----------+
866| :c:data:`PyExc_IsADirectoryError` | :exc:`IsADirectoryError` | |
867+-----------------------------------------+---------------------------------+----------+
868| :c:data:`PyExc_KeyError` | :exc:`KeyError` | |
869+-----------------------------------------+---------------------------------+----------+
870| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | |
871+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900872| :c:data:`PyExc_LookupError` | :exc:`LookupError` | \(1) |
873+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200874| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | |
875+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900876| :c:data:`PyExc_ModuleNotFoundError` | :exc:`ModuleNotFoundError` | |
877+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200878| :c:data:`PyExc_NameError` | :exc:`NameError` | |
879+-----------------------------------------+---------------------------------+----------+
880| :c:data:`PyExc_NotADirectoryError` | :exc:`NotADirectoryError` | |
881+-----------------------------------------+---------------------------------+----------+
882| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | |
883+-----------------------------------------+---------------------------------+----------+
884| :c:data:`PyExc_OSError` | :exc:`OSError` | \(1) |
885+-----------------------------------------+---------------------------------+----------+
886| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | |
887+-----------------------------------------+---------------------------------+----------+
888| :c:data:`PyExc_PermissionError` | :exc:`PermissionError` | |
889+-----------------------------------------+---------------------------------+----------+
890| :c:data:`PyExc_ProcessLookupError` | :exc:`ProcessLookupError` | |
891+-----------------------------------------+---------------------------------+----------+
Yury Selivanovf488fb42015-07-03 01:04:23 -0400892| :c:data:`PyExc_RecursionError` | :exc:`RecursionError` | |
893+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200894| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) |
895+-----------------------------------------+---------------------------------+----------+
896| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | |
897+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900898| :c:data:`PyExc_StopAsyncIteration` | :exc:`StopAsyncIteration` | |
899+-----------------------------------------+---------------------------------+----------+
900| :c:data:`PyExc_StopIteration` | :exc:`StopIteration` | |
901+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200902| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | |
903+-----------------------------------------+---------------------------------+----------+
904| :c:data:`PyExc_SystemError` | :exc:`SystemError` | |
905+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200906| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | |
907+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900908| :c:data:`PyExc_TabError` | :exc:`TabError` | |
909+-----------------------------------------+---------------------------------+----------+
910| :c:data:`PyExc_TimeoutError` | :exc:`TimeoutError` | |
911+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200912| :c:data:`PyExc_TypeError` | :exc:`TypeError` | |
913+-----------------------------------------+---------------------------------+----------+
cocoatomoe8c76312017-04-02 19:45:40 +0900914| :c:data:`PyExc_UnboundLocalError` | :exc:`UnboundLocalError` | |
915+-----------------------------------------+---------------------------------+----------+
916| :c:data:`PyExc_UnicodeDecodeError` | :exc:`UnicodeDecodeError` | |
917+-----------------------------------------+---------------------------------+----------+
918| :c:data:`PyExc_UnicodeEncodeError` | :exc:`UnicodeEncodeError` | |
919+-----------------------------------------+---------------------------------+----------+
920| :c:data:`PyExc_UnicodeError` | :exc:`UnicodeError` | |
921+-----------------------------------------+---------------------------------+----------+
922| :c:data:`PyExc_UnicodeTranslateError` | :exc:`UnicodeTranslateError` | |
923+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200924| :c:data:`PyExc_ValueError` | :exc:`ValueError` | |
925+-----------------------------------------+---------------------------------+----------+
926| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | |
927+-----------------------------------------+---------------------------------+----------+
928
929.. versionadded:: 3.3
930 :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
931 :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
932 :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
933 :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
934 :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
935 :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
936 :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
937 and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
938
Yury Selivanovf488fb42015-07-03 01:04:23 -0400939.. versionadded:: 3.5
cocoatomoe8c76312017-04-02 19:45:40 +0900940 :c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`.
Yury Selivanovf488fb42015-07-03 01:04:23 -0400941
cocoatomoe8c76312017-04-02 19:45:40 +0900942.. versionadded:: 3.6
943 :c:data:`PyExc_ModuleNotFoundError`.
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200944
945These are compatibility aliases to :c:data:`PyExc_OSError`:
946
cocoatomoe8c76312017-04-02 19:45:40 +0900947.. index::
948 single: PyExc_EnvironmentError
949 single: PyExc_IOError
950 single: PyExc_WindowsError
951
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200952+-------------------------------------+----------+
953| C Name | Notes |
954+=====================================+==========+
955| :c:data:`PyExc_EnvironmentError` | |
956+-------------------------------------+----------+
957| :c:data:`PyExc_IOError` | |
958+-------------------------------------+----------+
959| :c:data:`PyExc_WindowsError` | \(3) |
960+-------------------------------------+----------+
961
962.. versionchanged:: 3.3
963 These aliases used to be separate exception types.
964
Georg Brandl116aa622007-08-15 14:28:22 +0000965Notes:
966
967(1)
968 This is a base class for other standard exceptions.
969
970(2)
971 This is the same as :exc:`weakref.ReferenceError`.
972
973(3)
974 Only defined on Windows; protect code that uses this by testing that the
975 preprocessor macro ``MS_WINDOWS`` is defined.
cocoatomoe8c76312017-04-02 19:45:40 +0900976
delirious-lettuce3378b202017-05-19 14:37:57 -0600977.. _standardwarningcategories:
cocoatomoeaeda642017-04-15 11:06:02 +0900978
979Standard Warning Categories
980===========================
cocoatomoe8c76312017-04-02 19:45:40 +0900981
982All standard Python warning categories are available as global variables whose
983names are ``PyExc_`` followed by the Python exception name. These have the type
984:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
985the variables:
986
987.. index::
988 single: PyExc_Warning
989 single: PyExc_BytesWarning
delirious-lettuce3378b202017-05-19 14:37:57 -0600990 single: PyExc_DeprecationWarning
cocoatomoe8c76312017-04-02 19:45:40 +0900991 single: PyExc_FutureWarning
992 single: PyExc_ImportWarning
993 single: PyExc_PendingDeprecationWarning
994 single: PyExc_ResourceWarning
995 single: PyExc_RuntimeWarning
996 single: PyExc_SyntaxWarning
997 single: PyExc_UnicodeWarning
998 single: PyExc_UserWarning
999
1000+------------------------------------------+---------------------------------+----------+
1001| C Name | Python Name | Notes |
1002+==========================================+=================================+==========+
1003| :c:data:`PyExc_Warning` | :exc:`Warning` | \(1) |
1004+------------------------------------------+---------------------------------+----------+
1005| :c:data:`PyExc_BytesWarning` | :exc:`BytesWarning` | |
1006+------------------------------------------+---------------------------------+----------+
1007| :c:data:`PyExc_DeprecationWarning` | :exc:`DeprecationWarning` | |
1008+------------------------------------------+---------------------------------+----------+
1009| :c:data:`PyExc_FutureWarning` | :exc:`FutureWarning` | |
1010+------------------------------------------+---------------------------------+----------+
1011| :c:data:`PyExc_ImportWarning` | :exc:`ImportWarning` | |
1012+------------------------------------------+---------------------------------+----------+
delirious-lettuce3378b202017-05-19 14:37:57 -06001013| :c:data:`PyExc_PendingDeprecationWarning`| :exc:`PendingDeprecationWarning`| |
cocoatomoe8c76312017-04-02 19:45:40 +09001014+------------------------------------------+---------------------------------+----------+
1015| :c:data:`PyExc_ResourceWarning` | :exc:`ResourceWarning` | |
1016+------------------------------------------+---------------------------------+----------+
1017| :c:data:`PyExc_RuntimeWarning` | :exc:`RuntimeWarning` | |
1018+------------------------------------------+---------------------------------+----------+
1019| :c:data:`PyExc_SyntaxWarning` | :exc:`SyntaxWarning` | |
1020+------------------------------------------+---------------------------------+----------+
1021| :c:data:`PyExc_UnicodeWarning` | :exc:`UnicodeWarning` | |
1022+------------------------------------------+---------------------------------+----------+
1023| :c:data:`PyExc_UserWarning` | :exc:`UserWarning` | |
1024+------------------------------------------+---------------------------------+----------+
1025
1026.. versionadded:: 3.2
1027 :c:data:`PyExc_ResourceWarning`.
1028
1029Notes:
1030
1031(1)
1032 This is a base class for other standard warning categories.