blob: 5644410b47ed9673863a2047b257e865abd3ac7e [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.
56 Call this function only when the error indicator is set. (Otherwise it will
57 cause a fatal error!)
58
Georg Brandl115fb352009-02-05 10:56:37 +000059 If *set_sys_last_vars* is nonzero, the variables :data:`sys.last_type`,
60 :data:`sys.last_value` and :data:`sys.last_traceback` will be set to the
61 type, value and traceback of the printed exception, respectively.
62
63
Georg Brandl60203b42010-10-06 10:11:56 +000064.. c:function:: void PyErr_Print()
Georg Brandl115fb352009-02-05 10:56:37 +000065
66 Alias for ``PyErr_PrintEx(1)``.
67
Georg Brandl116aa622007-08-15 14:28:22 +000068
Antoine Pitrou550ff722014-09-30 21:56:10 +020069.. c:function:: void PyErr_WriteUnraisable(PyObject *obj)
Georg Brandl116aa622007-08-15 14:28:22 +000070
Antoine Pitrou550ff722014-09-30 21:56:10 +020071 This utility function prints a warning message to ``sys.stderr`` when an
72 exception has been set but it is impossible for the interpreter to actually
73 raise the exception. It is used, for example, when an exception occurs in an
74 :meth:`__del__` method.
Georg Brandl116aa622007-08-15 14:28:22 +000075
Antoine Pitrou550ff722014-09-30 21:56:10 +020076 The function is called with a single argument *obj* that identifies the context
Martin Panter3263f682016-02-28 03:16:11 +000077 in which the unraisable exception occurred. If possible,
78 the repr of *obj* will be printed in the warning message.
Georg Brandl116aa622007-08-15 14:28:22 +000079
80
Antoine Pitrou550ff722014-09-30 21:56:10 +020081Raising exceptions
82==================
Georg Brandl116aa622007-08-15 14:28:22 +000083
Antoine Pitrou550ff722014-09-30 21:56:10 +020084These functions help you set the current thread's error indicator.
85For convenience, some of these functions will always return a
86NULL pointer for use in a ``return`` statement.
Martin v. Löwisaa2efcb2012-04-19 14:33:43 +020087
88
Georg Brandl60203b42010-10-06 10:11:56 +000089.. c:function:: void PyErr_SetString(PyObject *type, const char *message)
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 This is the most common way to set the error indicator. The first argument
92 specifies the exception type; it is normally one of the standard exceptions,
Georg Brandl60203b42010-10-06 10:11:56 +000093 e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count.
Victor Stinner257d38f2010-10-09 10:12:11 +000094 The second argument is an error message; it is decoded from ``'utf-8``'.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96
Georg Brandl60203b42010-10-06 10:11:56 +000097.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)
Georg Brandl116aa622007-08-15 14:28:22 +000098
Georg Brandl60203b42010-10-06 10:11:56 +000099 This function is similar to :c:func:`PyErr_SetString` but lets you specify an
Georg Brandl116aa622007-08-15 14:28:22 +0000100 arbitrary Python object for the "value" of the exception.
101
102
Georg Brandl60203b42010-10-06 10:11:56 +0000103.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Antoine Pitroua66e0292010-11-27 20:40:43 +0000105 This function sets the error indicator and returns *NULL*. *exception*
106 should be a Python exception class. The *format* and subsequent
107 parameters help format the error message; they have the same meaning and
Victor Stinnerb1dbd102010-12-28 11:02:46 +0000108 values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
Victor Stinner555a24f2010-12-27 01:49:26 +0000109 string.
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +0000110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Antoine Pitrou0676a402014-09-30 21:16:27 +0200112.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
113
Georg Brandl93a56cd2014-10-30 22:25:41 +0100114 Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather
Antoine Pitrou0676a402014-09-30 21:16:27 +0200115 than a variable number of arguments.
116
117 .. versionadded:: 3.5
118
119
Georg Brandl60203b42010-10-06 10:11:56 +0000120.. c:function:: void PyErr_SetNone(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122 This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
123
124
Georg Brandl60203b42010-10-06 10:11:56 +0000125.. c:function:: int PyErr_BadArgument()
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127 This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
128 *message* indicates that a built-in operation was invoked with an illegal
129 argument. It is mostly for internal use.
130
131
Georg Brandl60203b42010-10-06 10:11:56 +0000132.. c:function:: PyObject* PyErr_NoMemory()
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134 This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL*
135 so an object allocation function can write ``return PyErr_NoMemory();`` when it
136 runs out of memory.
137
138
Georg Brandl60203b42010-10-06 10:11:56 +0000139.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141 .. index:: single: strerror()
142
143 This is a convenience function to raise an exception when a C library function
Georg Brandl60203b42010-10-06 10:11:56 +0000144 has returned an error and set the C variable :c:data:`errno`. It constructs a
145 tuple object whose first item is the integer :c:data:`errno` value and whose
146 second item is the corresponding error message (gotten from :c:func:`strerror`),
Georg Brandl116aa622007-08-15 14:28:22 +0000147 and then calls ``PyErr_SetObject(type, object)``. On Unix, when the
Georg Brandl60203b42010-10-06 10:11:56 +0000148 :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call,
149 this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator,
Georg Brandl116aa622007-08-15 14:28:22 +0000150 leaves it set to that. The function always returns *NULL*, so a wrapper
151 function around a system call can write ``return PyErr_SetFromErrno(type);``
152 when the system call returns an error.
153
154
Georg Brandl991fc572013-04-14 11:12:16 +0200155.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Georg Brandl60203b42010-10-06 10:11:56 +0000157 Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
Georg Brandl991fc572013-04-14 11:12:16 +0200158 *filenameObject* is not *NULL*, it is passed to the constructor of *type* as
Andrew Svetlov08af0002014-04-01 01:13:30 +0300159 a third parameter. In the case of :exc:`OSError` exception,
160 this is used to define the :attr:`filename` attribute of the
Georg Brandl991fc572013-04-14 11:12:16 +0200161 exception instance.
162
163
Larry Hastingsb0827312014-02-09 22:05:19 -0800164.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
165
166 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but takes a second
167 filename object, for raising errors when a function that takes two filenames
168 fails.
169
Georg Brandldf48b972014-03-24 09:06:18 +0100170 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800171
172
Georg Brandl991fc572013-04-14 11:12:16 +0200173.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
174
175 Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename
176 is given as a C string. *filename* is decoded from the filesystem encoding
Victor Stinner14e461d2013-08-26 22:28:21 +0200177 (:func:`os.fsdecode`).
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179
Georg Brandl60203b42010-10-06 10:11:56 +0000180.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 This is a convenience function to raise :exc:`WindowsError`. If called with
Georg Brandl60203b42010-10-06 10:11:56 +0000183 *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError`
184 is used instead. It calls the Win32 function :c:func:`FormatMessage` to retrieve
185 the Windows description of error code given by *ierr* or :c:func:`GetLastError`,
Georg Brandl116aa622007-08-15 14:28:22 +0000186 then it constructs a tuple object whose first item is the *ierr* value and whose
187 second item is the corresponding error message (gotten from
Georg Brandl60203b42010-10-06 10:11:56 +0000188 :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
Georg Brandl116aa622007-08-15 14:28:22 +0000189 object)``. This function always returns *NULL*. Availability: Windows.
190
191
Georg Brandl60203b42010-10-06 10:11:56 +0000192.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Georg Brandl60203b42010-10-06 10:11:56 +0000194 Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
Georg Brandl116aa622007-08-15 14:28:22 +0000195 specifying the exception type to be raised. Availability: Windows.
196
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Georg Brandl60203b42010-10-06 10:11:56 +0000198.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000199
Georg Brandl991fc572013-04-14 11:12:16 +0200200 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
201 filename is given as a C string. *filename* is decoded from the filesystem
Victor Stinner14e461d2013-08-26 22:28:21 +0200202 encoding (:func:`os.fsdecode`). Availability: Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204
Georg Brandl991fc572013-04-14 11:12:16 +0200205.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)
206
207 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, with an
208 additional parameter specifying the exception type to be raised.
209 Availability: Windows.
210
211
Larry Hastingsb0827312014-02-09 22:05:19 -0800212.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
213
214 Similar to :c:func:`PyErr_SetExcFromWindowsErrWithFilenameObject`,
215 but accepts a second filename object.
216 Availability: Windows.
217
Georg Brandldf48b972014-03-24 09:06:18 +0100218 .. versionadded:: 3.4
Larry Hastingsb0827312014-02-09 22:05:19 -0800219
220
Georg Brandl991fc572013-04-14 11:12:16 +0200221.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Georg Brandl60203b42010-10-06 10:11:56 +0000223 Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
Georg Brandl116aa622007-08-15 14:28:22 +0000224 parameter specifying the exception type to be raised. Availability: Windows.
225
Georg Brandlf4095832012-04-24 19:16:24 +0200226
Brian Curtin09b86d12012-04-17 16:57:09 -0500227.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Brian Curtinbd439742012-04-16 15:14:36 -0500228
229 This is a convenience function to raise :exc:`ImportError`. *msg* will be
Brian Curtin09b86d12012-04-17 16:57:09 -0500230 set as the exception's message string. *name* and *path*, both of which can
231 be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name``
232 and ``path`` attributes.
Brian Curtinbd439742012-04-16 15:14:36 -0500233
Brian Curtinbded8942012-04-16 18:14:09 -0500234 .. versionadded:: 3.3
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Georg Brandlf4095832012-04-24 19:16:24 +0200236
Victor Stinner14e461d2013-08-26 22:28:21 +0200237.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000238
239 Set file, line, and offset information for the current exception. If the
240 current exception is not a :exc:`SyntaxError`, then it sets additional
241 attributes, which make the exception printing subsystem think the exception
Victor Stinner14e461d2013-08-26 22:28:21 +0200242 is a :exc:`SyntaxError`.
Benjamin Peterson2c539712010-09-20 22:42:10 +0000243
Georg Brandldf48b972014-03-24 09:06:18 +0100244 .. versionadded:: 3.4
Victor Stinner14e461d2013-08-26 22:28:21 +0200245
246
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300247.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Victor Stinner14e461d2013-08-26 22:28:21 +0200248
249 Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
250 decoded from the filesystem encoding (:func:`os.fsdecode`).
251
Georg Brandldf48b972014-03-24 09:06:18 +0100252 .. versionadded:: 3.2
Benjamin Petersonb5d23b42010-09-21 21:29:26 +0000253
Benjamin Peterson2c539712010-09-20 22:42:10 +0000254
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300255.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
Benjamin Peterson2c539712010-09-20 22:42:10 +0000256
Victor Stinner14e461d2013-08-26 22:28:21 +0200257 Like :c:func:`PyErr_SyntaxLocationEx`, but the col_offset parameter is
Benjamin Peterson2c539712010-09-20 22:42:10 +0000258 omitted.
259
260
Georg Brandl60203b42010-10-06 10:11:56 +0000261.. c:function:: void PyErr_BadInternalCall()
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000263 This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
264 where *message* indicates that an internal operation (e.g. a Python/C API
265 function) was invoked with an illegal argument. It is mostly for internal
266 use.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
Antoine Pitrou550ff722014-09-30 21:56:10 +0200269Issuing warnings
270================
271
272Use these functions to issue warnings from C code. They mirror similar
273functions exported by the Python :mod:`warnings` module. They normally
274print a warning message to *sys.stderr*; however, it is
275also possible that the user has specified that warnings are to be turned into
276errors, and in that case they will raise an exception. It is also possible that
277the functions raise an exception because of a problem with the warning machinery.
278The return value is ``0`` if no exception is raised, or ``-1`` if an exception
279is raised. (It is not possible to determine whether a warning message is
280actually printed, nor what the reason is for the exception; this is
281intentional.) If an exception is raised, the caller should do its normal
282exception handling (for example, :c:func:`Py_DECREF` owned references and return
283an error value).
284
Georg Brandl97435162014-10-06 12:58:00 +0200285.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287 Issue a warning message. The *category* argument is a warning category (see
Martin Panter6245cb32016-04-15 02:14:19 +0000288 below) or *NULL*; the *message* argument is a UTF-8 encoded string. *stack_level* is a
Georg Brandl116aa622007-08-15 14:28:22 +0000289 positive number giving a number of stack frames; the warning will be issued from
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000290 the currently executing line of code in that stack frame. A *stack_level* of 1
Georg Brandl60203b42010-10-06 10:11:56 +0000291 is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that,
Georg Brandl116aa622007-08-15 14:28:22 +0000292 and so forth.
293
Georg Brandl60203b42010-10-06 10:11:56 +0000294 Warning categories must be subclasses of :c:data:`Warning`; the default warning
295 category is :c:data:`RuntimeWarning`. The standard Python warning categories are
Georg Brandl116aa622007-08-15 14:28:22 +0000296 available as global variables whose names are ``PyExc_`` followed by the Python
Georg Brandl60203b42010-10-06 10:11:56 +0000297 exception name. These have the type :c:type:`PyObject\*`; they are all class
298 objects. Their names are :c:data:`PyExc_Warning`, :c:data:`PyExc_UserWarning`,
299 :c:data:`PyExc_UnicodeWarning`, :c:data:`PyExc_DeprecationWarning`,
300 :c:data:`PyExc_SyntaxWarning`, :c:data:`PyExc_RuntimeWarning`, and
301 :c:data:`PyExc_FutureWarning`. :c:data:`PyExc_Warning` is a subclass of
302 :c:data:`PyExc_Exception`; the other warning categories are subclasses of
303 :c:data:`PyExc_Warning`.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305 For information about warning control, see the documentation for the
306 :mod:`warnings` module and the :option:`-W` option in the command line
307 documentation. There is no C API for warning control.
308
309
Victor Stinner14e461d2013-08-26 22:28:21 +0200310.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312 Issue a warning message with explicit control over all warning attributes. This
313 is a straightforward wrapper around the Python function
314 :func:`warnings.warn_explicit`, see there for more information. The *module*
315 and *registry* arguments may be set to *NULL* to get the default effect
Victor Stinner14e461d2013-08-26 22:28:21 +0200316 described there.
317
318 .. versionadded:: 3.4
319
320
321.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
322
323 Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and
324 *module* are UTF-8 encoded strings, and *filename* is decoded from the
325 filesystem encoding (:func:`os.fsdecode`).
Georg Brandl116aa622007-08-15 14:28:22 +0000326
327
Georg Brandl60203b42010-10-06 10:11:56 +0000328.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000329
Georg Brandl60203b42010-10-06 10:11:56 +0000330 Function similar to :c:func:`PyErr_WarnEx`, but use
Victor Stinner555a24f2010-12-27 01:49:26 +0000331 :c:func:`PyUnicode_FromFormat` to format the warning message. *format* is
332 an ASCII-encoded string.
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000333
334 .. versionadded:: 3.2
335
Georg Brandlf4095832012-04-24 19:16:24 +0200336
Victor Stinner914cde82016-03-19 01:03:51 +0100337.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
338
339 Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
340 :exc:`ResourceWarning` and pass *source* to :func:`warnings.WarningMessage`.
341
342 .. versionadded:: 3.6
343
344
Antoine Pitrou550ff722014-09-30 21:56:10 +0200345Querying the error indicator
346============================
347
348.. c:function:: PyObject* PyErr_Occurred()
349
350 Test whether the error indicator is set. If set, return the exception *type*
351 (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
352 functions or to :c:func:`PyErr_Restore`). If not set, return *NULL*. You do not
353 own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
354 it.
355
356 .. note::
357
358 Do not compare the return value to a specific exception; use
359 :c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could
360 easily fail since the exception may be an instance instead of a class, in the
Benjamin Peterson610bc6a2015-01-13 09:20:31 -0500361 case of a class exception, or it may be a subclass of the expected exception.)
Antoine Pitrou550ff722014-09-30 21:56:10 +0200362
363
364.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
365
366 Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This
367 should only be called when an exception is actually set; a memory access
368 violation will occur if no exception has been raised.
369
370
371.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
372
373 Return true if the *given* exception matches the exception type in *exc*. If
374 *exc* is a class object, this also returns true when *given* is an instance
375 of a subclass. If *exc* is a tuple, all exception types in the tuple (and
376 recursively in subtuples) are searched for a match.
377
378
379.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
380
381 Retrieve the error indicator into three variables whose addresses are passed.
382 If the error indicator is not set, set all three variables to *NULL*. If it is
383 set, it will be cleared and you own a reference to each object retrieved. The
384 value and traceback object may be *NULL* even when the type object is not.
385
386 .. note::
387
388 This function is normally only used by code that needs to catch exceptions or
389 by code that needs to save and restore the error indicator temporarily, e.g.::
390
391 {
392 PyObject **type, **value, **traceback;
393 PyErr_Fetch(&type, &value, &traceback);
394
395 /* ... code that might produce other errors ... */
396
397 PyErr_Restore(type, value, traceback);
398 }
399
400
401.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
402
403 Set the error indicator from the three objects. If the error indicator is
404 already set, it is cleared first. If the objects are *NULL*, the error
405 indicator is cleared. Do not pass a *NULL* type and non-*NULL* value or
406 traceback. The exception type should be a class. Do not pass an invalid
407 exception type or value. (Violating these rules will cause subtle problems
408 later.) This call takes away a reference to each object: you must own a
409 reference to each object before the call and after the call you no longer own
410 these references. (If you don't understand this, don't use this function. I
411 warned you.)
412
413 .. note::
414
415 This function is normally only used by code that needs to save and restore the
416 error indicator temporarily. Use :c:func:`PyErr_Fetch` to save the current
417 error indicator.
418
419
420.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
421
422 Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
423 can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
424 not an instance of the same class. This function can be used to instantiate
425 the class in that case. If the values are already normalized, nothing happens.
426 The delayed normalization is implemented to improve performance.
427
428 .. note::
429
430 This function *does not* implicitly set the ``__traceback__``
431 attribute on the exception value. If setting the traceback
432 appropriately is desired, the following additional snippet is needed::
433
434 if (tb != NULL) {
435 PyException_SetTraceback(val, tb);
436 }
437
438
439.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
440
441 Retrieve the exception info, as known from ``sys.exc_info()``. This refers
442 to an exception that was *already caught*, not to an exception that was
443 freshly raised. Returns new references for the three objects, any of which
444 may be *NULL*. Does not modify the exception info state.
445
446 .. note::
447
448 This function is not normally used by code that wants to handle exceptions.
449 Rather, it can be used when code needs to save and restore the exception
450 state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the
451 exception state.
452
453 .. versionadded:: 3.3
454
455
456.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
457
458 Set the exception info, as known from ``sys.exc_info()``. This refers
459 to an exception that was *already caught*, not to an exception that was
460 freshly raised. This function steals the references of the arguments.
461 To clear the exception state, pass *NULL* for all three arguments.
462 For general rules about the three arguments, see :c:func:`PyErr_Restore`.
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_GetExcInfo` to read the exception
469 state.
470
471 .. versionadded:: 3.3
472
473
474Signal Handling
475===============
476
477
Georg Brandl60203b42010-10-06 10:11:56 +0000478.. c:function:: int PyErr_CheckSignals()
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480 .. index::
481 module: signal
482 single: SIGINT
483 single: KeyboardInterrupt (built-in exception)
484
485 This function interacts with Python's signal handling. It checks whether a
486 signal has been sent to the processes and if so, invokes the corresponding
487 signal handler. If the :mod:`signal` module is supported, this can invoke a
488 signal handler written in Python. In all cases, the default effect for
489 :const:`SIGINT` is to raise the :exc:`KeyboardInterrupt` exception. If an
490 exception is raised the error indicator is set and the function returns ``-1``;
491 otherwise the function returns ``0``. The error indicator may or may not be
492 cleared if it was previously set.
493
494
Georg Brandl60203b42010-10-06 10:11:56 +0000495.. c:function:: void PyErr_SetInterrupt()
Georg Brandl116aa622007-08-15 14:28:22 +0000496
497 .. index::
498 single: SIGINT
499 single: KeyboardInterrupt (built-in exception)
500
501 This function simulates the effect of a :const:`SIGINT` signal arriving --- the
Georg Brandl60203b42010-10-06 10:11:56 +0000502 next time :c:func:`PyErr_CheckSignals` is called, :exc:`KeyboardInterrupt` will
Georg Brandl116aa622007-08-15 14:28:22 +0000503 be raised. It may be called without holding the interpreter lock.
504
505 .. % XXX This was described as obsolete, but is used in
Georg Brandl2067bfd2008-05-25 13:05:15 +0000506 .. % _thread.interrupt_main() (used from IDLE), so it's still needed.
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508
Georg Brandl60203b42010-10-06 10:11:56 +0000509.. c:function:: int PySignal_SetWakeupFd(int fd)
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000510
Victor Stinner11517102014-07-29 23:31:34 +0200511 This utility function specifies a file descriptor to which the signal number
512 is written as a single byte whenever a signal is received. *fd* must be
513 non-blocking. It returns the previous such file descriptor.
514
515 The value ``-1`` disables the feature; this is the initial state.
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000516 This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
517 error checking. *fd* should be a valid file descriptor. The function should
518 only be called from the main thread.
519
Victor Stinner11517102014-07-29 23:31:34 +0200520 .. versionchanged:: 3.5
521 On Windows, the function now also supports socket handles.
522
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000523
Antoine Pitrou550ff722014-09-30 21:56:10 +0200524Exception Classes
525=================
526
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300527.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Georg Brandl325eb472011-07-13 15:59:24 +0200529 This utility function creates and returns a new exception class. The *name*
Georg Brandl116aa622007-08-15 14:28:22 +0000530 argument must be the name of the new exception, a C string of the form
Georg Brandl325eb472011-07-13 15:59:24 +0200531 ``module.classname``. The *base* and *dict* arguments are normally *NULL*.
532 This creates a class object derived from :exc:`Exception` (accessible in C as
Georg Brandl60203b42010-10-06 10:11:56 +0000533 :c:data:`PyExc_Exception`).
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535 The :attr:`__module__` attribute of the new class is set to the first part (up
536 to the last dot) of the *name* argument, and the class name is set to the last
537 part (after the last dot). The *base* argument can be used to specify alternate
538 base classes; it can either be only one class or a tuple of classes. The *dict*
539 argument can be used to specify a dictionary of class variables and methods.
540
541
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300542.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
Georg Brandl1e28a272009-12-28 08:41:01 +0000543
Georg Brandl60203b42010-10-06 10:11:56 +0000544 Same as :c:func:`PyErr_NewException`, except that the new exception class can
Georg Brandl1e28a272009-12-28 08:41:01 +0000545 easily be given a docstring: If *doc* is non-*NULL*, it will be used as the
546 docstring for the exception class.
547
548 .. versionadded:: 3.2
549
550
Georg Brandlab6f2f62009-03-31 04:16:10 +0000551Exception Objects
552=================
553
Georg Brandl60203b42010-10-06 10:11:56 +0000554.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000555
556 Return the traceback associated with the exception as a new reference, as
557 accessible from Python through :attr:`__traceback__`. If there is no
558 traceback associated, this returns *NULL*.
559
560
Georg Brandl60203b42010-10-06 10:11:56 +0000561.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000562
563 Set the traceback associated with the exception to *tb*. Use ``Py_None`` to
564 clear it.
565
566
Georg Brandl60203b42010-10-06 10:11:56 +0000567.. c:function:: PyObject* PyException_GetContext(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000568
569 Return the context (another exception instance during whose handling *ex* was
570 raised) associated with the exception as a new reference, as accessible from
571 Python through :attr:`__context__`. If there is no context associated, this
572 returns *NULL*.
573
574
Georg Brandl60203b42010-10-06 10:11:56 +0000575.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000576
577 Set the context associated with the exception to *ctx*. Use *NULL* to clear
578 it. There is no type check to make sure that *ctx* is an exception instance.
579 This steals a reference to *ctx*.
580
581
Georg Brandl60203b42010-10-06 10:11:56 +0000582.. c:function:: PyObject* PyException_GetCause(PyObject *ex)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000583
Nick Coghlanab7bf212012-02-26 17:49:52 +1000584 Return the cause (either an exception instance, or :const:`None`,
585 set by ``raise ... from ...``) associated with the exception as a new
586 reference, as accessible from Python through :attr:`__cause__`.
587
Georg Brandlab6f2f62009-03-31 04:16:10 +0000588
Larry Hastings3732ed22014-03-15 21:13:56 -0700589.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
Georg Brandlab6f2f62009-03-31 04:16:10 +0000590
Larry Hastings3732ed22014-03-15 21:13:56 -0700591 Set the cause associated with the exception to *cause*. Use *NULL* to clear
592 it. There is no type check to make sure that *cause* is either an exception
593 instance or :const:`None`. This steals a reference to *cause*.
Nick Coghlanab7bf212012-02-26 17:49:52 +1000594
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700595 :attr:`__suppress_context__` is implicitly set to ``True`` by this function.
Georg Brandlab6f2f62009-03-31 04:16:10 +0000596
597
Georg Brandl5a932652010-11-23 07:54:19 +0000598.. _unicodeexceptions:
599
600Unicode Exception Objects
601=========================
602
603The following functions are used to create and modify Unicode exceptions from C.
604
605.. 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)
606
607 Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000608 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
609 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000610
611.. 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)
612
613 Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
Victor Stinner555a24f2010-12-27 01:49:26 +0000614 *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
615 UTF-8 encoded strings.
Georg Brandl5a932652010-11-23 07:54:19 +0000616
617.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
618
619 Create a :class:`UnicodeTranslateError` object with the attributes *object*,
Martin Panter6245cb32016-04-15 02:14:19 +0000620 *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string.
Georg Brandl5a932652010-11-23 07:54:19 +0000621
622.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
623 PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
624
625 Return the *encoding* attribute of the given exception object.
626
627.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
628 PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
629 PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
630
631 Return the *object* attribute of the given exception object.
632
633.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
634 int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
635 int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
636
637 Get the *start* attribute of the given exception object and place it into
638 *\*start*. *start* must not be *NULL*. Return ``0`` on success, ``-1`` on
639 failure.
640
641.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
642 int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
643 int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
644
645 Set the *start* attribute of the given exception object to *start*. Return
646 ``0`` on success, ``-1`` on failure.
647
648.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
649 int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
650 int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
651
652 Get the *end* attribute of the given exception object and place it into
653 *\*end*. *end* must not be *NULL*. Return ``0`` on success, ``-1`` on
654 failure.
655
656.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
657 int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
658 int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
659
660 Set the *end* attribute of the given exception object to *end*. Return ``0``
661 on success, ``-1`` on failure.
662
663.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
664 PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
665 PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
666
667 Return the *reason* attribute of the given exception object.
668
669.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
670 int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
671 int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
672
673 Set the *reason* attribute of the given exception object to *reason*. Return
674 ``0`` on success, ``-1`` on failure.
675
676
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000677Recursion Control
678=================
679
680These two functions provide a way to perform safe recursive calls at the C
681level, both in the core and in extension modules. They are needed if the
682recursive code does not necessarily invoke Python code (which tracks its
683recursion depth automatically).
684
Serhiy Storchaka5fa22fc2015-06-21 16:26:28 +0300685.. c:function:: int Py_EnterRecursiveCall(const char *where)
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000686
687 Marks a point where a recursive C-level call is about to be performed.
688
Ezio Melottif1064492011-10-19 11:06:26 +0300689 If :const:`USE_STACKCHECK` is defined, this function checks if the OS
Georg Brandl60203b42010-10-06 10:11:56 +0000690 stack overflowed using :c:func:`PyOS_CheckStack`. In this is the case, it
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000691 sets a :exc:`MemoryError` and returns a nonzero value.
692
693 The function then checks if the recursion limit is reached. If this is the
Yury Selivanovf488fb42015-07-03 01:04:23 -0400694 case, a :exc:`RecursionError` is set and a nonzero value is returned.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000695 Otherwise, zero is returned.
696
697 *where* should be a string such as ``" in instance check"`` to be
Yury Selivanovf488fb42015-07-03 01:04:23 -0400698 concatenated to the :exc:`RecursionError` message caused by the recursion
699 depth limit.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000700
Georg Brandl60203b42010-10-06 10:11:56 +0000701.. c:function:: void Py_LeaveRecursiveCall()
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000702
Georg Brandl60203b42010-10-06 10:11:56 +0000703 Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each
704 *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000705
Antoine Pitrou39668f52013-08-01 21:12:45 +0200706Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000707special recursion handling. In addition to protecting the stack,
Antoine Pitrou39668f52013-08-01 21:12:45 +0200708:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000709following two functions facilitate this functionality. Effectively,
710these are the C equivalent to :func:`reprlib.recursive_repr`.
711
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000712.. c:function:: int Py_ReprEnter(PyObject *object)
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000713
Antoine Pitrou39668f52013-08-01 21:12:45 +0200714 Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000715 detect cycles.
716
717 If the object has already been processed, the function returns a
Antoine Pitrou39668f52013-08-01 21:12:45 +0200718 positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000719 should return a string object indicating a cycle. As examples,
720 :class:`dict` objects return ``{...}`` and :class:`list` objects
721 return ``[...]``.
722
723 The function will return a negative integer if the recursion limit
Antoine Pitrou39668f52013-08-01 21:12:45 +0200724 is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000725 typically return ``NULL``.
726
Antoine Pitrou39668f52013-08-01 21:12:45 +0200727 Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000728 implementation can continue normally.
729
730.. c:function:: void Py_ReprLeave(PyObject *object)
731
Daniel Stutzbachc5895dc2010-12-17 22:28:07 +0000732 Ends a :c:func:`Py_ReprEnter`. Must be called once for each
733 invocation of :c:func:`Py_ReprEnter` that returns zero.
Daniel Stutzbach7cb30512010-12-17 16:31:32 +0000734
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000735
Georg Brandl116aa622007-08-15 14:28:22 +0000736.. _standardexceptions:
737
738Standard Exceptions
739===================
740
741All standard Python exceptions are available as global variables whose names are
742``PyExc_`` followed by the Python exception name. These have the type
Georg Brandl60203b42010-10-06 10:11:56 +0000743:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
Georg Brandl116aa622007-08-15 14:28:22 +0000744the variables:
745
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200746+-----------------------------------------+---------------------------------+----------+
747| C Name | Python Name | Notes |
748+=========================================+=================================+==========+
749| :c:data:`PyExc_BaseException` | :exc:`BaseException` | \(1) |
750+-----------------------------------------+---------------------------------+----------+
751| :c:data:`PyExc_Exception` | :exc:`Exception` | \(1) |
752+-----------------------------------------+---------------------------------+----------+
753| :c:data:`PyExc_ArithmeticError` | :exc:`ArithmeticError` | \(1) |
754+-----------------------------------------+---------------------------------+----------+
755| :c:data:`PyExc_LookupError` | :exc:`LookupError` | \(1) |
756+-----------------------------------------+---------------------------------+----------+
757| :c:data:`PyExc_AssertionError` | :exc:`AssertionError` | |
758+-----------------------------------------+---------------------------------+----------+
759| :c:data:`PyExc_AttributeError` | :exc:`AttributeError` | |
760+-----------------------------------------+---------------------------------+----------+
761| :c:data:`PyExc_BlockingIOError` | :exc:`BlockingIOError` | |
762+-----------------------------------------+---------------------------------+----------+
763| :c:data:`PyExc_BrokenPipeError` | :exc:`BrokenPipeError` | |
764+-----------------------------------------+---------------------------------+----------+
765| :c:data:`PyExc_ChildProcessError` | :exc:`ChildProcessError` | |
766+-----------------------------------------+---------------------------------+----------+
767| :c:data:`PyExc_ConnectionError` | :exc:`ConnectionError` | |
768+-----------------------------------------+---------------------------------+----------+
769| :c:data:`PyExc_ConnectionAbortedError` | :exc:`ConnectionAbortedError` | |
770+-----------------------------------------+---------------------------------+----------+
771| :c:data:`PyExc_ConnectionRefusedError` | :exc:`ConnectionRefusedError` | |
772+-----------------------------------------+---------------------------------+----------+
773| :c:data:`PyExc_ConnectionResetError` | :exc:`ConnectionResetError` | |
774+-----------------------------------------+---------------------------------+----------+
775| :c:data:`PyExc_FileExistsError` | :exc:`FileExistsError` | |
776+-----------------------------------------+---------------------------------+----------+
777| :c:data:`PyExc_FileNotFoundError` | :exc:`FileNotFoundError` | |
778+-----------------------------------------+---------------------------------+----------+
779| :c:data:`PyExc_EOFError` | :exc:`EOFError` | |
780+-----------------------------------------+---------------------------------+----------+
781| :c:data:`PyExc_FloatingPointError` | :exc:`FloatingPointError` | |
782+-----------------------------------------+---------------------------------+----------+
783| :c:data:`PyExc_ImportError` | :exc:`ImportError` | |
784+-----------------------------------------+---------------------------------+----------+
Eric Snowc9432652016-09-07 15:42:32 -0700785| :c:data:`PyExc_ModuleNotFoundError` | :exc:`ModuleNotFoundError` | |
786+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200787| :c:data:`PyExc_IndexError` | :exc:`IndexError` | |
788+-----------------------------------------+---------------------------------+----------+
789| :c:data:`PyExc_InterruptedError` | :exc:`InterruptedError` | |
790+-----------------------------------------+---------------------------------+----------+
791| :c:data:`PyExc_IsADirectoryError` | :exc:`IsADirectoryError` | |
792+-----------------------------------------+---------------------------------+----------+
793| :c:data:`PyExc_KeyError` | :exc:`KeyError` | |
794+-----------------------------------------+---------------------------------+----------+
795| :c:data:`PyExc_KeyboardInterrupt` | :exc:`KeyboardInterrupt` | |
796+-----------------------------------------+---------------------------------+----------+
797| :c:data:`PyExc_MemoryError` | :exc:`MemoryError` | |
798+-----------------------------------------+---------------------------------+----------+
799| :c:data:`PyExc_NameError` | :exc:`NameError` | |
800+-----------------------------------------+---------------------------------+----------+
801| :c:data:`PyExc_NotADirectoryError` | :exc:`NotADirectoryError` | |
802+-----------------------------------------+---------------------------------+----------+
803| :c:data:`PyExc_NotImplementedError` | :exc:`NotImplementedError` | |
804+-----------------------------------------+---------------------------------+----------+
805| :c:data:`PyExc_OSError` | :exc:`OSError` | \(1) |
806+-----------------------------------------+---------------------------------+----------+
807| :c:data:`PyExc_OverflowError` | :exc:`OverflowError` | |
808+-----------------------------------------+---------------------------------+----------+
809| :c:data:`PyExc_PermissionError` | :exc:`PermissionError` | |
810+-----------------------------------------+---------------------------------+----------+
811| :c:data:`PyExc_ProcessLookupError` | :exc:`ProcessLookupError` | |
812+-----------------------------------------+---------------------------------+----------+
Yury Selivanovf488fb42015-07-03 01:04:23 -0400813| :c:data:`PyExc_RecursionError` | :exc:`RecursionError` | |
814+-----------------------------------------+---------------------------------+----------+
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200815| :c:data:`PyExc_ReferenceError` | :exc:`ReferenceError` | \(2) |
816+-----------------------------------------+---------------------------------+----------+
817| :c:data:`PyExc_RuntimeError` | :exc:`RuntimeError` | |
818+-----------------------------------------+---------------------------------+----------+
819| :c:data:`PyExc_SyntaxError` | :exc:`SyntaxError` | |
820+-----------------------------------------+---------------------------------+----------+
821| :c:data:`PyExc_SystemError` | :exc:`SystemError` | |
822+-----------------------------------------+---------------------------------+----------+
823| :c:data:`PyExc_TimeoutError` | :exc:`TimeoutError` | |
824+-----------------------------------------+---------------------------------+----------+
825| :c:data:`PyExc_SystemExit` | :exc:`SystemExit` | |
826+-----------------------------------------+---------------------------------+----------+
827| :c:data:`PyExc_TypeError` | :exc:`TypeError` | |
828+-----------------------------------------+---------------------------------+----------+
829| :c:data:`PyExc_ValueError` | :exc:`ValueError` | |
830+-----------------------------------------+---------------------------------+----------+
831| :c:data:`PyExc_ZeroDivisionError` | :exc:`ZeroDivisionError` | |
832+-----------------------------------------+---------------------------------+----------+
833
834.. versionadded:: 3.3
835 :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
836 :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
837 :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
838 :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
839 :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
840 :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
841 :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
842 and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
843
Yury Selivanovf488fb42015-07-03 01:04:23 -0400844.. versionadded:: 3.5
845 :c:data:`PyExc_RecursionError`.
846
Antoine Pitrou9a4a3422011-10-12 18:28:01 +0200847
848These are compatibility aliases to :c:data:`PyExc_OSError`:
849
850+-------------------------------------+----------+
851| C Name | Notes |
852+=====================================+==========+
853| :c:data:`PyExc_EnvironmentError` | |
854+-------------------------------------+----------+
855| :c:data:`PyExc_IOError` | |
856+-------------------------------------+----------+
857| :c:data:`PyExc_WindowsError` | \(3) |
858+-------------------------------------+----------+
859
860.. versionchanged:: 3.3
861 These aliases used to be separate exception types.
862
Georg Brandl116aa622007-08-15 14:28:22 +0000863
864.. index::
865 single: PyExc_BaseException
866 single: PyExc_Exception
867 single: PyExc_ArithmeticError
868 single: PyExc_LookupError
869 single: PyExc_AssertionError
870 single: PyExc_AttributeError
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200871 single: PyExc_BlockingIOError
872 single: PyExc_BrokenPipeError
873 single: PyExc_ConnectionError
874 single: PyExc_ConnectionAbortedError
875 single: PyExc_ConnectionRefusedError
876 single: PyExc_ConnectionResetError
Georg Brandl116aa622007-08-15 14:28:22 +0000877 single: PyExc_EOFError
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200878 single: PyExc_FileExistsError
879 single: PyExc_FileNotFoundError
Georg Brandl116aa622007-08-15 14:28:22 +0000880 single: PyExc_FloatingPointError
Georg Brandl116aa622007-08-15 14:28:22 +0000881 single: PyExc_ImportError
882 single: PyExc_IndexError
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200883 single: PyExc_InterruptedError
884 single: PyExc_IsADirectoryError
Georg Brandl116aa622007-08-15 14:28:22 +0000885 single: PyExc_KeyError
886 single: PyExc_KeyboardInterrupt
887 single: PyExc_MemoryError
888 single: PyExc_NameError
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200889 single: PyExc_NotADirectoryError
Georg Brandl116aa622007-08-15 14:28:22 +0000890 single: PyExc_NotImplementedError
891 single: PyExc_OSError
892 single: PyExc_OverflowError
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200893 single: PyExc_PermissionError
894 single: PyExc_ProcessLookupError
Yury Selivanovf488fb42015-07-03 01:04:23 -0400895 single: PyExc_RecursionError
Georg Brandl116aa622007-08-15 14:28:22 +0000896 single: PyExc_ReferenceError
897 single: PyExc_RuntimeError
898 single: PyExc_SyntaxError
899 single: PyExc_SystemError
900 single: PyExc_SystemExit
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200901 single: PyExc_TimeoutError
Georg Brandl116aa622007-08-15 14:28:22 +0000902 single: PyExc_TypeError
903 single: PyExc_ValueError
Georg Brandl116aa622007-08-15 14:28:22 +0000904 single: PyExc_ZeroDivisionError
Antoine Pitrou23a580f2011-10-12 18:33:15 +0200905 single: PyExc_EnvironmentError
906 single: PyExc_IOError
907 single: PyExc_WindowsError
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909Notes:
910
911(1)
912 This is a base class for other standard exceptions.
913
914(2)
915 This is the same as :exc:`weakref.ReferenceError`.
916
917(3)
918 Only defined on Windows; protect code that uses this by testing that the
919 preprocessor macro ``MS_WINDOWS`` is defined.