~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-3.5.2-docs-html/_sources/c-api/exceptions.txt

  • Committer: Dave Kuhlman
  • Date: 2017-04-15 16:24:56 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20170415162456-iav9vozzg4iwqwv3
Updated docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
.. highlightlang:: c
 
2
 
 
3
 
 
4
.. _exceptionhandling:
 
5
 
 
6
******************
 
7
Exception Handling
 
8
******************
 
9
 
 
10
The functions described in this chapter will let you handle and raise Python
 
11
exceptions.  It is important to understand some of the basics of Python
 
12
exception handling.  It works somewhat like the POSIX :c:data:`errno` variable:
 
13
there is a global indicator (per thread) of the last error that occurred.  Most
 
14
C API functions don't clear this on success, but will set it to indicate the
 
15
cause of the error on failure.  Most C API functions also return an error
 
16
indicator, usually *NULL* if they are supposed to return a pointer, or ``-1``
 
17
if they return an integer (exception: the :c:func:`PyArg_\*` functions
 
18
return ``1`` for success and ``0`` for failure).
 
19
 
 
20
Concretely, the error indicator consists of three object pointers: the
 
21
exception's type, the exception's value, and the traceback object.  Any
 
22
of those pointers can be NULL if non-set (although some combinations are
 
23
forbidden, for example you can't have a non-NULL traceback if the exception
 
24
type is NULL).
 
25
 
 
26
When a function must fail because some function it called failed, it generally
 
27
doesn't set the error indicator; the function it called already set it.  It is
 
28
responsible for either handling the error and clearing the exception or
 
29
returning after cleaning up any resources it holds (such as object references or
 
30
memory allocations); it should *not* continue normally if it is not prepared to
 
31
handle the error.  If returning due to an error, it is important to indicate to
 
32
the caller that an error has been set.  If the error is not handled or carefully
 
33
propagated, additional calls into the Python/C API may not behave as intended
 
34
and may fail in mysterious ways.
 
35
 
 
36
.. note::
 
37
   The error indicator is **not** the result of :func:`sys.exc_info()`.
 
38
   The former corresponds to an exception that is not yet caught (and is
 
39
   therefore still propagating), while the latter returns an exception after
 
40
   it is caught (and has therefore stopped propagating).
 
41
 
 
42
 
 
43
Printing and clearing
 
44
=====================
 
45
 
 
46
 
 
47
.. c:function:: void PyErr_Clear()
 
48
 
 
49
   Clear the error indicator.  If the error indicator is not set, there is no
 
50
   effect.
 
51
 
 
52
 
 
53
.. c:function:: void PyErr_PrintEx(int set_sys_last_vars)
 
54
 
 
55
   Print a standard traceback to ``sys.stderr`` and clear the error indicator.
 
56
   Call this function only when the error indicator is set.  (Otherwise it will
 
57
   cause a fatal error!)
 
58
 
 
59
   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
 
 
64
.. c:function:: void PyErr_Print()
 
65
 
 
66
   Alias for ``PyErr_PrintEx(1)``.
 
67
 
 
68
 
 
69
.. c:function:: void PyErr_WriteUnraisable(PyObject *obj)
 
70
 
 
71
   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.
 
75
 
 
76
   The function is called with a single argument *obj* that identifies the context
 
77
   in which the unraisable exception occurred. If possible,
 
78
   the repr of *obj* will be printed in the warning message.
 
79
 
 
80
 
 
81
Raising exceptions
 
82
==================
 
83
 
 
84
These functions help you set the current thread's error indicator.
 
85
For convenience, some of these functions will always return a
 
86
NULL pointer for use in a ``return`` statement.
 
87
 
 
88
 
 
89
.. c:function:: void PyErr_SetString(PyObject *type, const char *message)
 
90
 
 
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,
 
93
   e.g. :c:data:`PyExc_RuntimeError`.  You need not increment its reference count.
 
94
   The second argument is an error message; it is decoded from ``'utf-8``'.
 
95
 
 
96
 
 
97
.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)
 
98
 
 
99
   This function is similar to :c:func:`PyErr_SetString` but lets you specify an
 
100
   arbitrary Python object for the "value" of the exception.
 
101
 
 
102
 
 
103
.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
 
104
 
 
105
   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
 
108
   values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
 
109
   string.
 
110
 
 
111
 
 
112
.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
 
113
 
 
114
   Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather
 
115
   than a variable number of arguments.
 
116
 
 
117
   .. versionadded:: 3.5
 
118
 
 
119
 
 
120
.. c:function:: void PyErr_SetNone(PyObject *type)
 
121
 
 
122
   This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
 
123
 
 
124
 
 
125
.. c:function:: int PyErr_BadArgument()
 
126
 
 
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
 
 
132
.. c:function:: PyObject* PyErr_NoMemory()
 
133
 
 
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
 
 
139
.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
 
140
 
 
141
   .. index:: single: strerror()
 
142
 
 
143
   This is a convenience function to raise an exception when a C library function
 
144
   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`),
 
147
   and then calls ``PyErr_SetObject(type, object)``.  On Unix, when the
 
148
   :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,
 
150
   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
 
 
155
.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
 
156
 
 
157
   Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
 
158
   *filenameObject* is not *NULL*, it is passed to the constructor of *type* as
 
159
   a third parameter.  In the case of :exc:`OSError` exception,
 
160
   this is used to define the :attr:`filename` attribute of the
 
161
   exception instance.
 
162
 
 
163
 
 
164
.. 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
 
 
170
   .. versionadded:: 3.4
 
171
 
 
172
 
 
173
.. 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
 
177
   (:func:`os.fsdecode`).
 
178
 
 
179
 
 
180
.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
 
181
 
 
182
   This is a convenience function to raise :exc:`WindowsError`. If called with
 
183
   *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`,
 
186
   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
 
188
   :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
 
189
   object)``. This function always returns *NULL*. Availability: Windows.
 
190
 
 
191
 
 
192
.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
 
193
 
 
194
   Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
 
195
   specifying the exception type to be raised. Availability: Windows.
 
196
 
 
197
 
 
198
.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
 
199
 
 
200
   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
 
201
   filename is given as a C string.  *filename* is decoded from the filesystem
 
202
   encoding (:func:`os.fsdecode`).  Availability: Windows.
 
203
 
 
204
 
 
205
.. 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
 
 
212
.. 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
 
 
218
   .. versionadded:: 3.4
 
219
 
 
220
 
 
221
.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
 
222
 
 
223
   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
 
224
   parameter specifying the exception type to be raised. Availability: Windows.
 
225
 
 
226
 
 
227
.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
 
228
 
 
229
   This is a convenience function to raise :exc:`ImportError`. *msg* will be
 
230
   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.
 
233
 
 
234
   .. versionadded:: 3.3
 
235
 
 
236
 
 
237
.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
 
238
 
 
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
 
242
   is a :exc:`SyntaxError`.
 
243
 
 
244
   .. versionadded:: 3.4
 
245
 
 
246
 
 
247
.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
 
248
 
 
249
   Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
 
250
   decoded from the filesystem encoding (:func:`os.fsdecode`).
 
251
 
 
252
   .. versionadded:: 3.2
 
253
 
 
254
 
 
255
.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
 
256
 
 
257
   Like :c:func:`PyErr_SyntaxLocationEx`, but the col_offset parameter is
 
258
   omitted.
 
259
 
 
260
 
 
261
.. c:function:: void PyErr_BadInternalCall()
 
262
 
 
263
   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.
 
267
 
 
268
 
 
269
Issuing warnings
 
270
================
 
271
 
 
272
Use these functions to issue warnings from C code.  They mirror similar
 
273
functions exported by the Python :mod:`warnings` module.  They normally
 
274
print a warning message to *sys.stderr*; however, it is
 
275
also possible that the user has specified that warnings are to be turned into
 
276
errors, and in that case they will raise an exception.  It is also possible that
 
277
the functions raise an exception because of a problem with the warning machinery.
 
278
The return value is ``0`` if no exception is raised, or ``-1`` if an exception
 
279
is raised.  (It is not possible to determine whether a warning message is
 
280
actually printed, nor what the reason is for the exception; this is
 
281
intentional.)  If an exception is raised, the caller should do its normal
 
282
exception handling (for example, :c:func:`Py_DECREF` owned references and return
 
283
an error value).
 
284
 
 
285
.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
 
286
 
 
287
   Issue a warning message.  The *category* argument is a warning category (see
 
288
   below) or *NULL*; the *message* argument is a UTF-8 encoded string.  *stack_level* is a
 
289
   positive number giving a number of stack frames; the warning will be issued from
 
290
   the  currently executing line of code in that stack frame.  A *stack_level* of 1
 
291
   is the function calling :c:func:`PyErr_WarnEx`, 2 is  the function above that,
 
292
   and so forth.
 
293
 
 
294
   Warning categories must be subclasses of :c:data:`Warning`; the default warning
 
295
   category is :c:data:`RuntimeWarning`.  The standard Python warning categories are
 
296
   available as global variables whose names are ``PyExc_`` followed by the Python
 
297
   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`.
 
304
 
 
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
 
 
310
.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
 
311
 
 
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
 
316
   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`).
 
326
 
 
327
 
 
328
.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
 
329
 
 
330
   Function similar to :c:func:`PyErr_WarnEx`, but use
 
331
   :c:func:`PyUnicode_FromFormat` to format the warning message.  *format* is
 
332
   an ASCII-encoded string.
 
333
 
 
334
   .. versionadded:: 3.2
 
335
 
 
336
 
 
337
Querying the error indicator
 
338
============================
 
339
 
 
340
.. c:function:: PyObject* PyErr_Occurred()
 
341
 
 
342
   Test whether the error indicator is set.  If set, return the exception *type*
 
343
   (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
 
344
   functions or to :c:func:`PyErr_Restore`).  If not set, return *NULL*.  You do not
 
345
   own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
 
346
   it.
 
347
 
 
348
   .. note::
 
349
 
 
350
      Do not compare the return value to a specific exception; use
 
351
      :c:func:`PyErr_ExceptionMatches` instead, shown below.  (The comparison could
 
352
      easily fail since the exception may be an instance instead of a class, in the
 
353
      case of a class exception, or it may be a subclass of the expected exception.)
 
354
 
 
355
 
 
356
.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
 
357
 
 
358
   Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``.  This
 
359
   should only be called when an exception is actually set; a memory access
 
360
   violation will occur if no exception has been raised.
 
361
 
 
362
 
 
363
.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
 
364
 
 
365
   Return true if the *given* exception matches the exception type in *exc*.  If
 
366
   *exc* is a class object, this also returns true when *given* is an instance
 
367
   of a subclass.  If *exc* is a tuple, all exception types in the tuple (and
 
368
   recursively in subtuples) are searched for a match.
 
369
 
 
370
 
 
371
.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
 
372
 
 
373
   Retrieve the error indicator into three variables whose addresses are passed.
 
374
   If the error indicator is not set, set all three variables to *NULL*.  If it is
 
375
   set, it will be cleared and you own a reference to each object retrieved.  The
 
376
   value and traceback object may be *NULL* even when the type object is not.
 
377
 
 
378
   .. note::
 
379
 
 
380
      This function is normally only used by code that needs to catch exceptions or
 
381
      by code that needs to save and restore the error indicator temporarily, e.g.::
 
382
 
 
383
         {
 
384
            PyObject **type, **value, **traceback;
 
385
            PyErr_Fetch(&type, &value, &traceback);
 
386
 
 
387
            /* ... code that might produce other errors ... */
 
388
 
 
389
            PyErr_Restore(type, value, traceback);
 
390
         }
 
391
 
 
392
 
 
393
.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
 
394
 
 
395
   Set  the error indicator from the three objects.  If the error indicator is
 
396
   already set, it is cleared first.  If the objects are *NULL*, the error
 
397
   indicator is cleared.  Do not pass a *NULL* type and non-*NULL* value or
 
398
   traceback.  The exception type should be a class.  Do not pass an invalid
 
399
   exception type or value. (Violating these rules will cause subtle problems
 
400
   later.)  This call takes away a reference to each object: you must own a
 
401
   reference to each object before the call and after the call you no longer own
 
402
   these references.  (If you don't understand this, don't use this function.  I
 
403
   warned you.)
 
404
 
 
405
   .. note::
 
406
 
 
407
      This function is normally only used by code that needs to save and restore the
 
408
      error indicator temporarily.  Use :c:func:`PyErr_Fetch` to save the current
 
409
      error indicator.
 
410
 
 
411
 
 
412
.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
 
413
 
 
414
   Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
 
415
   can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
 
416
   not an instance of the  same class.  This function can be used to instantiate
 
417
   the class in that case.  If the values are already normalized, nothing happens.
 
418
   The delayed normalization is implemented to improve performance.
 
419
 
 
420
   .. note::
 
421
 
 
422
      This function *does not* implicitly set the ``__traceback__``
 
423
      attribute on the exception value. If setting the traceback
 
424
      appropriately is desired, the following additional snippet is needed::
 
425
 
 
426
         if (tb != NULL) {
 
427
           PyException_SetTraceback(val, tb);
 
428
         }
 
429
 
 
430
 
 
431
.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
 
432
 
 
433
   Retrieve the exception info, as known from ``sys.exc_info()``.  This refers
 
434
   to an exception that was *already caught*, not to an exception that was
 
435
   freshly raised.  Returns new references for the three objects, any of which
 
436
   may be *NULL*.  Does not modify the exception info state.
 
437
 
 
438
   .. note::
 
439
 
 
440
      This function is not normally used by code that wants to handle exceptions.
 
441
      Rather, it can be used when code needs to save and restore the exception
 
442
      state temporarily.  Use :c:func:`PyErr_SetExcInfo` to restore or clear the
 
443
      exception state.
 
444
 
 
445
   .. versionadded:: 3.3
 
446
 
 
447
 
 
448
.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
 
449
 
 
450
   Set the exception info, as known from ``sys.exc_info()``.  This refers
 
451
   to an exception that was *already caught*, not to an exception that was
 
452
   freshly raised.  This function steals the references of the arguments.
 
453
   To clear the exception state, pass *NULL* for all three arguments.
 
454
   For general rules about the three arguments, see :c:func:`PyErr_Restore`.
 
455
 
 
456
   .. note::
 
457
 
 
458
      This function is not normally used by code that wants to handle exceptions.
 
459
      Rather, it can be used when code needs to save and restore the exception
 
460
      state temporarily.  Use :c:func:`PyErr_GetExcInfo` to read the exception
 
461
      state.
 
462
 
 
463
   .. versionadded:: 3.3
 
464
 
 
465
 
 
466
Signal Handling
 
467
===============
 
468
 
 
469
 
 
470
.. c:function:: int PyErr_CheckSignals()
 
471
 
 
472
   .. index::
 
473
      module: signal
 
474
      single: SIGINT
 
475
      single: KeyboardInterrupt (built-in exception)
 
476
 
 
477
   This function interacts with Python's signal handling.  It checks whether a
 
478
   signal has been sent to the processes and if so, invokes the corresponding
 
479
   signal handler.  If the :mod:`signal` module is supported, this can invoke a
 
480
   signal handler written in Python.  In all cases, the default effect for
 
481
   :const:`SIGINT` is to raise the  :exc:`KeyboardInterrupt` exception.  If an
 
482
   exception is raised the error indicator is set and the function returns ``-1``;
 
483
   otherwise the function returns ``0``.  The error indicator may or may not be
 
484
   cleared if it was previously set.
 
485
 
 
486
 
 
487
.. c:function:: void PyErr_SetInterrupt()
 
488
 
 
489
   .. index::
 
490
      single: SIGINT
 
491
      single: KeyboardInterrupt (built-in exception)
 
492
 
 
493
   This function simulates the effect of a :const:`SIGINT` signal arriving --- the
 
494
   next time :c:func:`PyErr_CheckSignals` is called,  :exc:`KeyboardInterrupt` will
 
495
   be raised.  It may be called without holding the interpreter lock.
 
496
 
 
497
   .. % XXX This was described as obsolete, but is used in
 
498
   .. % _thread.interrupt_main() (used from IDLE), so it's still needed.
 
499
 
 
500
 
 
501
.. c:function:: int PySignal_SetWakeupFd(int fd)
 
502
 
 
503
   This utility function specifies a file descriptor to which the signal number
 
504
   is written as a single byte whenever a signal is received. *fd* must be
 
505
   non-blocking. It returns the previous such file descriptor.
 
506
 
 
507
   The value ``-1`` disables the feature; this is the initial state.
 
508
   This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
 
509
   error checking.  *fd* should be a valid file descriptor.  The function should
 
510
   only be called from the main thread.
 
511
 
 
512
   .. versionchanged:: 3.5
 
513
      On Windows, the function now also supports socket handles.
 
514
 
 
515
 
 
516
Exception Classes
 
517
=================
 
518
 
 
519
.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
 
520
 
 
521
   This utility function creates and returns a new exception class. The *name*
 
522
   argument must be the name of the new exception, a C string of the form
 
523
   ``module.classname``.  The *base* and *dict* arguments are normally *NULL*.
 
524
   This creates a class object derived from :exc:`Exception` (accessible in C as
 
525
   :c:data:`PyExc_Exception`).
 
526
 
 
527
   The :attr:`__module__` attribute of the new class is set to the first part (up
 
528
   to the last dot) of the *name* argument, and the class name is set to the last
 
529
   part (after the last dot).  The *base* argument can be used to specify alternate
 
530
   base classes; it can either be only one class or a tuple of classes. The *dict*
 
531
   argument can be used to specify a dictionary of class variables and methods.
 
532
 
 
533
 
 
534
.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
 
535
 
 
536
   Same as :c:func:`PyErr_NewException`, except that the new exception class can
 
537
   easily be given a docstring: If *doc* is non-*NULL*, it will be used as the
 
538
   docstring for the exception class.
 
539
 
 
540
   .. versionadded:: 3.2
 
541
 
 
542
 
 
543
Exception Objects
 
544
=================
 
545
 
 
546
.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
 
547
 
 
548
   Return the traceback associated with the exception as a new reference, as
 
549
   accessible from Python through :attr:`__traceback__`.  If there is no
 
550
   traceback associated, this returns *NULL*.
 
551
 
 
552
 
 
553
.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
 
554
 
 
555
   Set the traceback associated with the exception to *tb*.  Use ``Py_None`` to
 
556
   clear it.
 
557
 
 
558
 
 
559
.. c:function:: PyObject* PyException_GetContext(PyObject *ex)
 
560
 
 
561
   Return the context (another exception instance during whose handling *ex* was
 
562
   raised) associated with the exception as a new reference, as accessible from
 
563
   Python through :attr:`__context__`.  If there is no context associated, this
 
564
   returns *NULL*.
 
565
 
 
566
 
 
567
.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
 
568
 
 
569
   Set the context associated with the exception to *ctx*.  Use *NULL* to clear
 
570
   it.  There is no type check to make sure that *ctx* is an exception instance.
 
571
   This steals a reference to *ctx*.
 
572
 
 
573
 
 
574
.. c:function:: PyObject* PyException_GetCause(PyObject *ex)
 
575
 
 
576
   Return the cause (either an exception instance, or :const:`None`,
 
577
   set by ``raise ... from ...``) associated with the exception as a new
 
578
   reference, as accessible from Python through :attr:`__cause__`.
 
579
 
 
580
 
 
581
.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
 
582
 
 
583
   Set the cause associated with the exception to *cause*.  Use *NULL* to clear
 
584
   it.  There is no type check to make sure that *cause* is either an exception
 
585
   instance or :const:`None`.  This steals a reference to *cause*.
 
586
 
 
587
   :attr:`__suppress_context__` is implicitly set to ``True`` by this function.
 
588
 
 
589
 
 
590
.. _unicodeexceptions:
 
591
 
 
592
Unicode Exception Objects
 
593
=========================
 
594
 
 
595
The following functions are used to create and modify Unicode exceptions from C.
 
596
 
 
597
.. 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)
 
598
 
 
599
   Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
 
600
   *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
 
601
   UTF-8 encoded strings.
 
602
 
 
603
.. 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)
 
604
 
 
605
   Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
 
606
   *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
 
607
   UTF-8 encoded strings.
 
608
 
 
609
.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
 
610
 
 
611
   Create a :class:`UnicodeTranslateError` object with the attributes *object*,
 
612
   *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string.
 
613
 
 
614
.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
 
615
                PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
 
616
 
 
617
   Return the *encoding* attribute of the given exception object.
 
618
 
 
619
.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
 
620
                PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
 
621
                PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
 
622
 
 
623
   Return the *object* attribute of the given exception object.
 
624
 
 
625
.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
 
626
                int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
 
627
                int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
 
628
 
 
629
   Get the *start* attribute of the given exception object and place it into
 
630
   *\*start*.  *start* must not be *NULL*.  Return ``0`` on success, ``-1`` on
 
631
   failure.
 
632
 
 
633
.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
 
634
                int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
 
635
                int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
 
636
 
 
637
   Set the *start* attribute of the given exception object to *start*.  Return
 
638
   ``0`` on success, ``-1`` on failure.
 
639
 
 
640
.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
 
641
                int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
 
642
                int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
 
643
 
 
644
   Get the *end* attribute of the given exception object and place it into
 
645
   *\*end*.  *end* must not be *NULL*.  Return ``0`` on success, ``-1`` on
 
646
   failure.
 
647
 
 
648
.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
 
649
                int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
 
650
                int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
 
651
 
 
652
   Set the *end* attribute of the given exception object to *end*.  Return ``0``
 
653
   on success, ``-1`` on failure.
 
654
 
 
655
.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
 
656
                PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
 
657
                PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
 
658
 
 
659
   Return the *reason* attribute of the given exception object.
 
660
 
 
661
.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
 
662
                int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
 
663
                int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
 
664
 
 
665
   Set the *reason* attribute of the given exception object to *reason*.  Return
 
666
   ``0`` on success, ``-1`` on failure.
 
667
 
 
668
 
 
669
Recursion Control
 
670
=================
 
671
 
 
672
These two functions provide a way to perform safe recursive calls at the C
 
673
level, both in the core and in extension modules.  They are needed if the
 
674
recursive code does not necessarily invoke Python code (which tracks its
 
675
recursion depth automatically).
 
676
 
 
677
.. c:function:: int Py_EnterRecursiveCall(const char *where)
 
678
 
 
679
   Marks a point where a recursive C-level call is about to be performed.
 
680
 
 
681
   If :const:`USE_STACKCHECK` is defined, this function checks if the OS
 
682
   stack overflowed using :c:func:`PyOS_CheckStack`.  In this is the case, it
 
683
   sets a :exc:`MemoryError` and returns a nonzero value.
 
684
 
 
685
   The function then checks if the recursion limit is reached.  If this is the
 
686
   case, a :exc:`RecursionError` is set and a nonzero value is returned.
 
687
   Otherwise, zero is returned.
 
688
 
 
689
   *where* should be a string such as ``" in instance check"`` to be
 
690
   concatenated to the :exc:`RecursionError` message caused by the recursion
 
691
   depth limit.
 
692
 
 
693
.. c:function:: void Py_LeaveRecursiveCall()
 
694
 
 
695
   Ends a :c:func:`Py_EnterRecursiveCall`.  Must be called once for each
 
696
   *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
 
697
 
 
698
Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
 
699
special recursion handling.  In addition to protecting the stack,
 
700
:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles.  The
 
701
following two functions facilitate this functionality.  Effectively,
 
702
these are the C equivalent to :func:`reprlib.recursive_repr`.
 
703
 
 
704
.. c:function:: int Py_ReprEnter(PyObject *object)
 
705
 
 
706
   Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
 
707
   detect cycles.
 
708
 
 
709
   If the object has already been processed, the function returns a
 
710
   positive integer.  In that case the :c:member:`~PyTypeObject.tp_repr` implementation
 
711
   should return a string object indicating a cycle.  As examples,
 
712
   :class:`dict` objects return ``{...}`` and :class:`list` objects
 
713
   return ``[...]``.
 
714
 
 
715
   The function will return a negative integer if the recursion limit
 
716
   is reached.  In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
 
717
   typically return ``NULL``.
 
718
 
 
719
   Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
 
720
   implementation can continue normally.
 
721
 
 
722
.. c:function:: void Py_ReprLeave(PyObject *object)
 
723
 
 
724
   Ends a :c:func:`Py_ReprEnter`.  Must be called once for each
 
725
   invocation of :c:func:`Py_ReprEnter` that returns zero.
 
726
 
 
727
 
 
728
.. _standardexceptions:
 
729
 
 
730
Standard Exceptions
 
731
===================
 
732
 
 
733
All standard Python exceptions are available as global variables whose names are
 
734
``PyExc_`` followed by the Python exception name.  These have the type
 
735
:c:type:`PyObject\*`; they are all class objects.  For completeness, here are all
 
736
the variables:
 
737
 
 
738
+-----------------------------------------+---------------------------------+----------+
 
739
| C Name                                  | Python Name                     | Notes    |
 
740
+=========================================+=================================+==========+
 
741
| :c:data:`PyExc_BaseException`           | :exc:`BaseException`            | \(1)     |
 
742
+-----------------------------------------+---------------------------------+----------+
 
743
| :c:data:`PyExc_Exception`               | :exc:`Exception`                | \(1)     |
 
744
+-----------------------------------------+---------------------------------+----------+
 
745
| :c:data:`PyExc_ArithmeticError`         | :exc:`ArithmeticError`          | \(1)     |
 
746
+-----------------------------------------+---------------------------------+----------+
 
747
| :c:data:`PyExc_LookupError`             | :exc:`LookupError`              | \(1)     |
 
748
+-----------------------------------------+---------------------------------+----------+
 
749
| :c:data:`PyExc_AssertionError`          | :exc:`AssertionError`           |          |
 
750
+-----------------------------------------+---------------------------------+----------+
 
751
| :c:data:`PyExc_AttributeError`          | :exc:`AttributeError`           |          |
 
752
+-----------------------------------------+---------------------------------+----------+
 
753
| :c:data:`PyExc_BlockingIOError`         | :exc:`BlockingIOError`          |          |
 
754
+-----------------------------------------+---------------------------------+----------+
 
755
| :c:data:`PyExc_BrokenPipeError`         | :exc:`BrokenPipeError`          |          |
 
756
+-----------------------------------------+---------------------------------+----------+
 
757
| :c:data:`PyExc_ChildProcessError`       | :exc:`ChildProcessError`        |          |
 
758
+-----------------------------------------+---------------------------------+----------+
 
759
| :c:data:`PyExc_ConnectionError`         | :exc:`ConnectionError`          |          |
 
760
+-----------------------------------------+---------------------------------+----------+
 
761
| :c:data:`PyExc_ConnectionAbortedError`  | :exc:`ConnectionAbortedError`   |          |
 
762
+-----------------------------------------+---------------------------------+----------+
 
763
| :c:data:`PyExc_ConnectionRefusedError`  | :exc:`ConnectionRefusedError`   |          |
 
764
+-----------------------------------------+---------------------------------+----------+
 
765
| :c:data:`PyExc_ConnectionResetError`    | :exc:`ConnectionResetError`     |          |
 
766
+-----------------------------------------+---------------------------------+----------+
 
767
| :c:data:`PyExc_FileExistsError`         | :exc:`FileExistsError`          |          |
 
768
+-----------------------------------------+---------------------------------+----------+
 
769
| :c:data:`PyExc_FileNotFoundError`       | :exc:`FileNotFoundError`        |          |
 
770
+-----------------------------------------+---------------------------------+----------+
 
771
| :c:data:`PyExc_EOFError`                | :exc:`EOFError`                 |          |
 
772
+-----------------------------------------+---------------------------------+----------+
 
773
| :c:data:`PyExc_FloatingPointError`      | :exc:`FloatingPointError`       |          |
 
774
+-----------------------------------------+---------------------------------+----------+
 
775
| :c:data:`PyExc_ImportError`             | :exc:`ImportError`              |          |
 
776
+-----------------------------------------+---------------------------------+----------+
 
777
| :c:data:`PyExc_IndexError`              | :exc:`IndexError`               |          |
 
778
+-----------------------------------------+---------------------------------+----------+
 
779
| :c:data:`PyExc_InterruptedError`        | :exc:`InterruptedError`         |          |
 
780
+-----------------------------------------+---------------------------------+----------+
 
781
| :c:data:`PyExc_IsADirectoryError`       | :exc:`IsADirectoryError`        |          |
 
782
+-----------------------------------------+---------------------------------+----------+
 
783
| :c:data:`PyExc_KeyError`                | :exc:`KeyError`                 |          |
 
784
+-----------------------------------------+---------------------------------+----------+
 
785
| :c:data:`PyExc_KeyboardInterrupt`       | :exc:`KeyboardInterrupt`        |          |
 
786
+-----------------------------------------+---------------------------------+----------+
 
787
| :c:data:`PyExc_MemoryError`             | :exc:`MemoryError`              |          |
 
788
+-----------------------------------------+---------------------------------+----------+
 
789
| :c:data:`PyExc_NameError`               | :exc:`NameError`                |          |
 
790
+-----------------------------------------+---------------------------------+----------+
 
791
| :c:data:`PyExc_NotADirectoryError`      | :exc:`NotADirectoryError`       |          |
 
792
+-----------------------------------------+---------------------------------+----------+
 
793
| :c:data:`PyExc_NotImplementedError`     | :exc:`NotImplementedError`      |          |
 
794
+-----------------------------------------+---------------------------------+----------+
 
795
| :c:data:`PyExc_OSError`                 | :exc:`OSError`                  | \(1)     |
 
796
+-----------------------------------------+---------------------------------+----------+
 
797
| :c:data:`PyExc_OverflowError`           | :exc:`OverflowError`            |          |
 
798
+-----------------------------------------+---------------------------------+----------+
 
799
| :c:data:`PyExc_PermissionError`         | :exc:`PermissionError`          |          |
 
800
+-----------------------------------------+---------------------------------+----------+
 
801
| :c:data:`PyExc_ProcessLookupError`      | :exc:`ProcessLookupError`       |          |
 
802
+-----------------------------------------+---------------------------------+----------+
 
803
| :c:data:`PyExc_RecursionError`          | :exc:`RecursionError`           |          |
 
804
+-----------------------------------------+---------------------------------+----------+
 
805
| :c:data:`PyExc_ReferenceError`          | :exc:`ReferenceError`           | \(2)     |
 
806
+-----------------------------------------+---------------------------------+----------+
 
807
| :c:data:`PyExc_RuntimeError`            | :exc:`RuntimeError`             |          |
 
808
+-----------------------------------------+---------------------------------+----------+
 
809
| :c:data:`PyExc_SyntaxError`             | :exc:`SyntaxError`              |          |
 
810
+-----------------------------------------+---------------------------------+----------+
 
811
| :c:data:`PyExc_SystemError`             | :exc:`SystemError`              |          |
 
812
+-----------------------------------------+---------------------------------+----------+
 
813
| :c:data:`PyExc_TimeoutError`            | :exc:`TimeoutError`             |          |
 
814
+-----------------------------------------+---------------------------------+----------+
 
815
| :c:data:`PyExc_SystemExit`              | :exc:`SystemExit`               |          |
 
816
+-----------------------------------------+---------------------------------+----------+
 
817
| :c:data:`PyExc_TypeError`               | :exc:`TypeError`                |          |
 
818
+-----------------------------------------+---------------------------------+----------+
 
819
| :c:data:`PyExc_ValueError`              | :exc:`ValueError`               |          |
 
820
+-----------------------------------------+---------------------------------+----------+
 
821
| :c:data:`PyExc_ZeroDivisionError`       | :exc:`ZeroDivisionError`        |          |
 
822
+-----------------------------------------+---------------------------------+----------+
 
823
 
 
824
.. versionadded:: 3.3
 
825
   :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
 
826
   :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
 
827
   :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
 
828
   :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
 
829
   :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
 
830
   :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
 
831
   :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
 
832
   and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
 
833
 
 
834
.. versionadded:: 3.5
 
835
   :c:data:`PyExc_RecursionError`.
 
836
 
 
837
 
 
838
These are compatibility aliases to :c:data:`PyExc_OSError`:
 
839
 
 
840
+-------------------------------------+----------+
 
841
| C Name                              | Notes    |
 
842
+=====================================+==========+
 
843
| :c:data:`PyExc_EnvironmentError`    |          |
 
844
+-------------------------------------+----------+
 
845
| :c:data:`PyExc_IOError`             |          |
 
846
+-------------------------------------+----------+
 
847
| :c:data:`PyExc_WindowsError`        | \(3)     |
 
848
+-------------------------------------+----------+
 
849
 
 
850
.. versionchanged:: 3.3
 
851
   These aliases used to be separate exception types.
 
852
 
 
853
 
 
854
.. index::
 
855
   single: PyExc_BaseException
 
856
   single: PyExc_Exception
 
857
   single: PyExc_ArithmeticError
 
858
   single: PyExc_LookupError
 
859
   single: PyExc_AssertionError
 
860
   single: PyExc_AttributeError
 
861
   single: PyExc_BlockingIOError
 
862
   single: PyExc_BrokenPipeError
 
863
   single: PyExc_ConnectionError
 
864
   single: PyExc_ConnectionAbortedError
 
865
   single: PyExc_ConnectionRefusedError
 
866
   single: PyExc_ConnectionResetError
 
867
   single: PyExc_EOFError
 
868
   single: PyExc_FileExistsError
 
869
   single: PyExc_FileNotFoundError
 
870
   single: PyExc_FloatingPointError
 
871
   single: PyExc_ImportError
 
872
   single: PyExc_IndexError
 
873
   single: PyExc_InterruptedError
 
874
   single: PyExc_IsADirectoryError
 
875
   single: PyExc_KeyError
 
876
   single: PyExc_KeyboardInterrupt
 
877
   single: PyExc_MemoryError
 
878
   single: PyExc_NameError
 
879
   single: PyExc_NotADirectoryError
 
880
   single: PyExc_NotImplementedError
 
881
   single: PyExc_OSError
 
882
   single: PyExc_OverflowError
 
883
   single: PyExc_PermissionError
 
884
   single: PyExc_ProcessLookupError
 
885
   single: PyExc_RecursionError
 
886
   single: PyExc_ReferenceError
 
887
   single: PyExc_RuntimeError
 
888
   single: PyExc_SyntaxError
 
889
   single: PyExc_SystemError
 
890
   single: PyExc_SystemExit
 
891
   single: PyExc_TimeoutError
 
892
   single: PyExc_TypeError
 
893
   single: PyExc_ValueError
 
894
   single: PyExc_ZeroDivisionError
 
895
   single: PyExc_EnvironmentError
 
896
   single: PyExc_IOError
 
897
   single: PyExc_WindowsError
 
898
 
 
899
Notes:
 
900
 
 
901
(1)
 
902
   This is a base class for other standard exceptions.
 
903
 
 
904
(2)
 
905
   This is the same as :exc:`weakref.ReferenceError`.
 
906
 
 
907
(3)
 
908
   Only defined on Windows; protect code that uses this by testing that the
 
909
   preprocessor macro ``MS_WINDOWS`` is defined.