• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. 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
12exception handling.  It works somewhat like the POSIX :c:data:`errno` variable:
13there is a global indicator (per thread) of the last error that occurred.  Most
14C 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).
25
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
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
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.
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   **Unless** the error is a ``SystemExit``.  In that case the no traceback
57   is printed and Python process will exit with the error code specified by
58   the ``SystemExit`` instance.
59
60   Call this function **only** when the error indicator is set.  Otherwise it
61   will cause a fatal error!
62
63   If *set_sys_last_vars* is nonzero, the variables :data:`sys.last_type`,
64   :data:`sys.last_value` and :data:`sys.last_traceback` will be set to the
65   type, value and traceback of the printed exception, respectively.
66
67
68.. c:function:: void PyErr_Print()
69
70   Alias for ``PyErr_PrintEx(1)``.
71
72
73.. c:function:: void PyErr_WriteUnraisable(PyObject *obj)
74
75   This utility function prints a warning message to ``sys.stderr`` when an
76   exception has been set but it is impossible for the interpreter to actually
77   raise the exception.  It is used, for example, when an exception occurs in an
78   :meth:`__del__` method.
79
80   The function is called with a single argument *obj* that identifies the context
81   in which the unraisable exception occurred. If possible,
82   the repr of *obj* will be printed in the warning message.
83
84
85Raising exceptions
86==================
87
88These functions help you set the current thread's error indicator.
89For convenience, some of these functions will always return a
90NULL pointer for use in a ``return`` statement.
91
92
93.. c:function:: void PyErr_SetString(PyObject *type, const char *message)
94
95   This is the most common way to set the error indicator.  The first argument
96   specifies the exception type; it is normally one of the standard exceptions,
97   e.g. :c:data:`PyExc_RuntimeError`.  You need not increment its reference count.
98   The second argument is an error message; it is decoded from ``'utf-8``'.
99
100
101.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)
102
103   This function is similar to :c:func:`PyErr_SetString` but lets you specify an
104   arbitrary Python object for the "value" of the exception.
105
106
107.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
108
109   This function sets the error indicator and returns *NULL*.  *exception*
110   should be a Python exception class.  The *format* and subsequent
111   parameters help format the error message; they have the same meaning and
112   values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
113   string.
114
115
116.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
117
118   Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather
119   than a variable number of arguments.
120
121   .. versionadded:: 3.5
122
123
124.. c:function:: void PyErr_SetNone(PyObject *type)
125
126   This is a shorthand for ``PyErr_SetObject(type, Py_None)``.
127
128
129.. c:function:: int PyErr_BadArgument()
130
131   This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
132   *message* indicates that a built-in operation was invoked with an illegal
133   argument.  It is mostly for internal use.
134
135
136.. c:function:: PyObject* PyErr_NoMemory()
137
138   This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL*
139   so an object allocation function can write ``return PyErr_NoMemory();`` when it
140   runs out of memory.
141
142
143.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)
144
145   .. index:: single: strerror()
146
147   This is a convenience function to raise an exception when a C library function
148   has returned an error and set the C variable :c:data:`errno`.  It constructs a
149   tuple object whose first item is the integer :c:data:`errno` value and whose
150   second item is the corresponding error message (gotten from :c:func:`strerror`),
151   and then calls ``PyErr_SetObject(type, object)``.  On Unix, when the
152   :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call,
153   this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator,
154   leaves it set to that.  The function always returns *NULL*, so a wrapper
155   function around a system call can write ``return PyErr_SetFromErrno(type);``
156   when the system call returns an error.
157
158
159.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
160
161   Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
162   *filenameObject* is not *NULL*, it is passed to the constructor of *type* as
163   a third parameter.  In the case of :exc:`OSError` exception,
164   this is used to define the :attr:`filename` attribute of the
165   exception instance.
166
167
168.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
169
170   Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but takes a second
171   filename object, for raising errors when a function that takes two filenames
172   fails.
173
174   .. versionadded:: 3.4
175
176
177.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
178
179   Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename
180   is given as a C string.  *filename* is decoded from the filesystem encoding
181   (:func:`os.fsdecode`).
182
183
184.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)
185
186   This is a convenience function to raise :exc:`WindowsError`. If called with
187   *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError`
188   is used instead.  It calls the Win32 function :c:func:`FormatMessage` to retrieve
189   the Windows description of error code given by *ierr* or :c:func:`GetLastError`,
190   then it constructs a tuple object whose first item is the *ierr* value and whose
191   second item is the corresponding error message (gotten from
192   :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
193   object)``. This function always returns *NULL*.
194
195   .. availability:: Windows.
196
197
198.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
199
200   Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
201   specifying the exception type to be raised.
202
203   .. availability:: Windows.
204
205
206.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
207
208   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
209   filename is given as a C string.  *filename* is decoded from the filesystem
210   encoding (:func:`os.fsdecode`).
211
212   .. availability:: Windows.
213
214
215.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)
216
217   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, with an
218   additional parameter specifying the exception type to be raised.
219
220   .. availability:: Windows.
221
222
223.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)
224
225   Similar to :c:func:`PyErr_SetExcFromWindowsErrWithFilenameObject`,
226   but accepts a second filename object.
227
228   .. availability:: Windows.
229
230   .. versionadded:: 3.4
231
232
233.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
234
235   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
236   parameter specifying the exception type to be raised.
237
238   .. availability:: Windows.
239
240
241.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
242
243   This is a convenience function to raise :exc:`ImportError`. *msg* will be
244   set as the exception's message string. *name* and *path*, both of which can
245   be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name``
246   and ``path`` attributes.
247
248   .. versionadded:: 3.3
249
250
251.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
252
253   Set file, line, and offset information for the current exception.  If the
254   current exception is not a :exc:`SyntaxError`, then it sets additional
255   attributes, which make the exception printing subsystem think the exception
256   is a :exc:`SyntaxError`.
257
258   .. versionadded:: 3.4
259
260
261.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
262
263   Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string
264   decoded from the filesystem encoding (:func:`os.fsdecode`).
265
266   .. versionadded:: 3.2
267
268
269.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno)
270
271   Like :c:func:`PyErr_SyntaxLocationEx`, but the col_offset parameter is
272   omitted.
273
274
275.. c:function:: void PyErr_BadInternalCall()
276
277   This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
278   where *message* indicates that an internal operation (e.g. a Python/C API
279   function) was invoked with an illegal argument.  It is mostly for internal
280   use.
281
282
283Issuing warnings
284================
285
286Use these functions to issue warnings from C code.  They mirror similar
287functions exported by the Python :mod:`warnings` module.  They normally
288print a warning message to *sys.stderr*; however, it is
289also possible that the user has specified that warnings are to be turned into
290errors, and in that case they will raise an exception.  It is also possible that
291the functions raise an exception because of a problem with the warning machinery.
292The return value is ``0`` if no exception is raised, or ``-1`` if an exception
293is raised.  (It is not possible to determine whether a warning message is
294actually printed, nor what the reason is for the exception; this is
295intentional.)  If an exception is raised, the caller should do its normal
296exception handling (for example, :c:func:`Py_DECREF` owned references and return
297an error value).
298
299.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
300
301   Issue a warning message.  The *category* argument is a warning category (see
302   below) or *NULL*; the *message* argument is a UTF-8 encoded string.  *stack_level* is a
303   positive number giving a number of stack frames; the warning will be issued from
304   the  currently executing line of code in that stack frame.  A *stack_level* of 1
305   is the function calling :c:func:`PyErr_WarnEx`, 2 is  the function above that,
306   and so forth.
307
308   Warning categories must be subclasses of :c:data:`PyExc_Warning`;
309   :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`;
310   the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard
311   Python warning categories are available as global variables whose names are
312   enumerated at :ref:`standardwarningcategories`.
313
314   For information about warning control, see the documentation for the
315   :mod:`warnings` module and the :option:`-W` option in the command line
316   documentation.  There is no C API for warning control.
317
318.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *msg, PyObject *name, PyObject *path)
319
320   Much like :c:func:`PyErr_SetImportError` but this function allows for
321   specifying a subclass of :exc:`ImportError` to raise.
322
323   .. versionadded:: 3.6
324
325
326.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)
327
328   Issue a warning message with explicit control over all warning attributes.  This
329   is a straightforward wrapper around the Python function
330   :func:`warnings.warn_explicit`, see there for more information.  The *module*
331   and *registry* arguments may be set to *NULL* to get the default effect
332   described there.
333
334   .. versionadded:: 3.4
335
336
337.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)
338
339   Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and
340   *module* are UTF-8 encoded strings, and *filename* is decoded from the
341   filesystem encoding (:func:`os.fsdecode`).
342
343
344.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
345
346   Function similar to :c:func:`PyErr_WarnEx`, but use
347   :c:func:`PyUnicode_FromFormat` to format the warning message.  *format* is
348   an ASCII-encoded string.
349
350   .. versionadded:: 3.2
351
352
353.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
354
355   Function similar to :c:func:`PyErr_WarnFormat`, but *category* is
356   :exc:`ResourceWarning` and pass *source* to :func:`warnings.WarningMessage`.
357
358   .. versionadded:: 3.6
359
360
361Querying the error indicator
362============================
363
364.. c:function:: PyObject* PyErr_Occurred()
365
366   Test whether the error indicator is set.  If set, return the exception *type*
367   (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
368   functions or to :c:func:`PyErr_Restore`).  If not set, return *NULL*.  You do not
369   own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
370   it.
371
372   .. note::
373
374      Do not compare the return value to a specific exception; use
375      :c:func:`PyErr_ExceptionMatches` instead, shown below.  (The comparison could
376      easily fail since the exception may be an instance instead of a class, in the
377      case of a class exception, or it may be a subclass of the expected exception.)
378
379
380.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)
381
382   Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``.  This
383   should only be called when an exception is actually set; a memory access
384   violation will occur if no exception has been raised.
385
386
387.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
388
389   Return true if the *given* exception matches the exception type in *exc*.  If
390   *exc* is a class object, this also returns true when *given* is an instance
391   of a subclass.  If *exc* is a tuple, all exception types in the tuple (and
392   recursively in subtuples) are searched for a match.
393
394
395.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
396
397   Retrieve the error indicator into three variables whose addresses are passed.
398   If the error indicator is not set, set all three variables to *NULL*.  If it is
399   set, it will be cleared and you own a reference to each object retrieved.  The
400   value and traceback object may be *NULL* even when the type object is not.
401
402   .. note::
403
404      This function is normally only used by code that needs to catch exceptions or
405      by code that needs to save and restore the error indicator temporarily, e.g.::
406
407         {
408            PyObject *type, *value, *traceback;
409            PyErr_Fetch(&type, &value, &traceback);
410
411            /* ... code that might produce other errors ... */
412
413            PyErr_Restore(type, value, traceback);
414         }
415
416
417.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
418
419   Set  the error indicator from the three objects.  If the error indicator is
420   already set, it is cleared first.  If the objects are *NULL*, the error
421   indicator is cleared.  Do not pass a *NULL* type and non-*NULL* value or
422   traceback.  The exception type should be a class.  Do not pass an invalid
423   exception type or value. (Violating these rules will cause subtle problems
424   later.)  This call takes away a reference to each object: you must own a
425   reference to each object before the call and after the call you no longer own
426   these references.  (If you don't understand this, don't use this function.  I
427   warned you.)
428
429   .. note::
430
431      This function is normally only used by code that needs to save and restore the
432      error indicator temporarily.  Use :c:func:`PyErr_Fetch` to save the current
433      error indicator.
434
435
436.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)
437
438   Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
439   can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
440   not an instance of the  same class.  This function can be used to instantiate
441   the class in that case.  If the values are already normalized, nothing happens.
442   The delayed normalization is implemented to improve performance.
443
444   .. note::
445
446      This function *does not* implicitly set the ``__traceback__``
447      attribute on the exception value. If setting the traceback
448      appropriately is desired, the following additional snippet is needed::
449
450         if (tb != NULL) {
451           PyException_SetTraceback(val, tb);
452         }
453
454
455.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
456
457   Retrieve the exception info, as known from ``sys.exc_info()``.  This refers
458   to an exception that was *already caught*, not to an exception that was
459   freshly raised.  Returns new references for the three objects, any of which
460   may be *NULL*.  Does not modify the exception info state.
461
462   .. note::
463
464      This function is not normally used by code that wants to handle exceptions.
465      Rather, it can be used when code needs to save and restore the exception
466      state temporarily.  Use :c:func:`PyErr_SetExcInfo` to restore or clear the
467      exception state.
468
469   .. versionadded:: 3.3
470
471
472.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
473
474   Set the exception info, as known from ``sys.exc_info()``.  This refers
475   to an exception that was *already caught*, not to an exception that was
476   freshly raised.  This function steals the references of the arguments.
477   To clear the exception state, pass *NULL* for all three arguments.
478   For general rules about the three arguments, see :c:func:`PyErr_Restore`.
479
480   .. note::
481
482      This function is not normally used by code that wants to handle exceptions.
483      Rather, it can be used when code needs to save and restore the exception
484      state temporarily.  Use :c:func:`PyErr_GetExcInfo` to read the exception
485      state.
486
487   .. versionadded:: 3.3
488
489
490Signal Handling
491===============
492
493
494.. c:function:: int PyErr_CheckSignals()
495
496   .. index::
497      module: signal
498      single: SIGINT
499      single: KeyboardInterrupt (built-in exception)
500
501   This function interacts with Python's signal handling.  It checks whether a
502   signal has been sent to the processes and if so, invokes the corresponding
503   signal handler.  If the :mod:`signal` module is supported, this can invoke a
504   signal handler written in Python.  In all cases, the default effect for
505   :const:`SIGINT` is to raise the  :exc:`KeyboardInterrupt` exception.  If an
506   exception is raised the error indicator is set and the function returns ``-1``;
507   otherwise the function returns ``0``.  The error indicator may or may not be
508   cleared if it was previously set.
509
510
511.. c:function:: void PyErr_SetInterrupt()
512
513   .. index::
514      single: SIGINT
515      single: KeyboardInterrupt (built-in exception)
516
517   This function simulates the effect of a :const:`SIGINT` signal arriving --- the
518   next time :c:func:`PyErr_CheckSignals` is called,  :exc:`KeyboardInterrupt` will
519   be raised.  It may be called without holding the interpreter lock.
520
521   .. % XXX This was described as obsolete, but is used in
522   .. % _thread.interrupt_main() (used from IDLE), so it's still needed.
523
524
525.. c:function:: int PySignal_SetWakeupFd(int fd)
526
527   This utility function specifies a file descriptor to which the signal number
528   is written as a single byte whenever a signal is received. *fd* must be
529   non-blocking. It returns the previous such file descriptor.
530
531   The value ``-1`` disables the feature; this is the initial state.
532   This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
533   error checking.  *fd* should be a valid file descriptor.  The function should
534   only be called from the main thread.
535
536   .. versionchanged:: 3.5
537      On Windows, the function now also supports socket handles.
538
539
540Exception Classes
541=================
542
543.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
544
545   This utility function creates and returns a new exception class. The *name*
546   argument must be the name of the new exception, a C string of the form
547   ``module.classname``.  The *base* and *dict* arguments are normally *NULL*.
548   This creates a class object derived from :exc:`Exception` (accessible in C as
549   :c:data:`PyExc_Exception`).
550
551   The :attr:`__module__` attribute of the new class is set to the first part (up
552   to the last dot) of the *name* argument, and the class name is set to the last
553   part (after the last dot).  The *base* argument can be used to specify alternate
554   base classes; it can either be only one class or a tuple of classes. The *dict*
555   argument can be used to specify a dictionary of class variables and methods.
556
557
558.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)
559
560   Same as :c:func:`PyErr_NewException`, except that the new exception class can
561   easily be given a docstring: If *doc* is non-*NULL*, it will be used as the
562   docstring for the exception class.
563
564   .. versionadded:: 3.2
565
566
567Exception Objects
568=================
569
570.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex)
571
572   Return the traceback associated with the exception as a new reference, as
573   accessible from Python through :attr:`__traceback__`.  If there is no
574   traceback associated, this returns *NULL*.
575
576
577.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb)
578
579   Set the traceback associated with the exception to *tb*.  Use ``Py_None`` to
580   clear it.
581
582
583.. c:function:: PyObject* PyException_GetContext(PyObject *ex)
584
585   Return the context (another exception instance during whose handling *ex* was
586   raised) associated with the exception as a new reference, as accessible from
587   Python through :attr:`__context__`.  If there is no context associated, this
588   returns *NULL*.
589
590
591.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx)
592
593   Set the context associated with the exception to *ctx*.  Use *NULL* to clear
594   it.  There is no type check to make sure that *ctx* is an exception instance.
595   This steals a reference to *ctx*.
596
597
598.. c:function:: PyObject* PyException_GetCause(PyObject *ex)
599
600   Return the cause (either an exception instance, or :const:`None`,
601   set by ``raise ... from ...``) associated with the exception as a new
602   reference, as accessible from Python through :attr:`__cause__`.
603
604
605.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause)
606
607   Set the cause associated with the exception to *cause*.  Use *NULL* to clear
608   it.  There is no type check to make sure that *cause* is either an exception
609   instance or :const:`None`.  This steals a reference to *cause*.
610
611   :attr:`__suppress_context__` is implicitly set to ``True`` by this function.
612
613
614.. _unicodeexceptions:
615
616Unicode Exception Objects
617=========================
618
619The following functions are used to create and modify Unicode exceptions from C.
620
621.. c:function:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
622
623   Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
624   *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
625   UTF-8 encoded strings.
626
627.. c:function:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
628
629   Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
630   *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
631   UTF-8 encoded strings.
632
633.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
634
635   Create a :class:`UnicodeTranslateError` object with the attributes *object*,
636   *length*, *start*, *end* and *reason*. *reason* is a UTF-8 encoded string.
637
638.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
639                PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
640
641   Return the *encoding* attribute of the given exception object.
642
643.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
644                PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
645                PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
646
647   Return the *object* attribute of the given exception object.
648
649.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
650                int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
651                int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
652
653   Get the *start* attribute of the given exception object and place it into
654   *\*start*.  *start* must not be *NULL*.  Return ``0`` on success, ``-1`` on
655   failure.
656
657.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
658                int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
659                int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
660
661   Set the *start* attribute of the given exception object to *start*.  Return
662   ``0`` on success, ``-1`` on failure.
663
664.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
665                int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
666                int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
667
668   Get the *end* attribute of the given exception object and place it into
669   *\*end*.  *end* must not be *NULL*.  Return ``0`` on success, ``-1`` on
670   failure.
671
672.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
673                int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
674                int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
675
676   Set the *end* attribute of the given exception object to *end*.  Return ``0``
677   on success, ``-1`` on failure.
678
679.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
680                PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
681                PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
682
683   Return the *reason* attribute of the given exception object.
684
685.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
686                int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
687                int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
688
689   Set the *reason* attribute of the given exception object to *reason*.  Return
690   ``0`` on success, ``-1`` on failure.
691
692
693Recursion Control
694=================
695
696These two functions provide a way to perform safe recursive calls at the C
697level, both in the core and in extension modules.  They are needed if the
698recursive code does not necessarily invoke Python code (which tracks its
699recursion depth automatically).
700
701.. c:function:: int Py_EnterRecursiveCall(const char *where)
702
703   Marks a point where a recursive C-level call is about to be performed.
704
705   If :const:`USE_STACKCHECK` is defined, this function checks if the OS
706   stack overflowed using :c:func:`PyOS_CheckStack`.  In this is the case, it
707   sets a :exc:`MemoryError` and returns a nonzero value.
708
709   The function then checks if the recursion limit is reached.  If this is the
710   case, a :exc:`RecursionError` is set and a nonzero value is returned.
711   Otherwise, zero is returned.
712
713   *where* should be a string such as ``" in instance check"`` to be
714   concatenated to the :exc:`RecursionError` message caused by the recursion
715   depth limit.
716
717.. c:function:: void Py_LeaveRecursiveCall()
718
719   Ends a :c:func:`Py_EnterRecursiveCall`.  Must be called once for each
720   *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
721
722Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires
723special recursion handling.  In addition to protecting the stack,
724:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles.  The
725following two functions facilitate this functionality.  Effectively,
726these are the C equivalent to :func:`reprlib.recursive_repr`.
727
728.. c:function:: int Py_ReprEnter(PyObject *object)
729
730   Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to
731   detect cycles.
732
733   If the object has already been processed, the function returns a
734   positive integer.  In that case the :c:member:`~PyTypeObject.tp_repr` implementation
735   should return a string object indicating a cycle.  As examples,
736   :class:`dict` objects return ``{...}`` and :class:`list` objects
737   return ``[...]``.
738
739   The function will return a negative integer if the recursion limit
740   is reached.  In that case the :c:member:`~PyTypeObject.tp_repr` implementation should
741   typically return ``NULL``.
742
743   Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr`
744   implementation can continue normally.
745
746.. c:function:: void Py_ReprLeave(PyObject *object)
747
748   Ends a :c:func:`Py_ReprEnter`.  Must be called once for each
749   invocation of :c:func:`Py_ReprEnter` that returns zero.
750
751
752.. _standardexceptions:
753
754Standard Exceptions
755===================
756
757All standard Python exceptions are available as global variables whose names are
758``PyExc_`` followed by the Python exception name.  These have the type
759:c:type:`PyObject\*`; they are all class objects.  For completeness, here are all
760the variables:
761
762.. index::
763   single: PyExc_BaseException
764   single: PyExc_Exception
765   single: PyExc_ArithmeticError
766   single: PyExc_AssertionError
767   single: PyExc_AttributeError
768   single: PyExc_BlockingIOError
769   single: PyExc_BrokenPipeError
770   single: PyExc_BufferError
771   single: PyExc_ChildProcessError
772   single: PyExc_ConnectionAbortedError
773   single: PyExc_ConnectionError
774   single: PyExc_ConnectionRefusedError
775   single: PyExc_ConnectionResetError
776   single: PyExc_EOFError
777   single: PyExc_FileExistsError
778   single: PyExc_FileNotFoundError
779   single: PyExc_FloatingPointError
780   single: PyExc_GeneratorExit
781   single: PyExc_ImportError
782   single: PyExc_IndentationError
783   single: PyExc_IndexError
784   single: PyExc_InterruptedError
785   single: PyExc_IsADirectoryError
786   single: PyExc_KeyError
787   single: PyExc_KeyboardInterrupt
788   single: PyExc_LookupError
789   single: PyExc_MemoryError
790   single: PyExc_ModuleNotFoundError
791   single: PyExc_NameError
792   single: PyExc_NotADirectoryError
793   single: PyExc_NotImplementedError
794   single: PyExc_OSError
795   single: PyExc_OverflowError
796   single: PyExc_PermissionError
797   single: PyExc_ProcessLookupError
798   single: PyExc_RecursionError
799   single: PyExc_ReferenceError
800   single: PyExc_RuntimeError
801   single: PyExc_StopAsyncIteration
802   single: PyExc_StopIteration
803   single: PyExc_SyntaxError
804   single: PyExc_SystemError
805   single: PyExc_SystemExit
806   single: PyExc_TabError
807   single: PyExc_TimeoutError
808   single: PyExc_TypeError
809   single: PyExc_UnboundLocalError
810   single: PyExc_UnicodeDecodeError
811   single: PyExc_UnicodeEncodeError
812   single: PyExc_UnicodeError
813   single: PyExc_UnicodeTranslateError
814   single: PyExc_ValueError
815   single: PyExc_ZeroDivisionError
816
817+-----------------------------------------+---------------------------------+----------+
818| C Name                                  | Python Name                     | Notes    |
819+=========================================+=================================+==========+
820| :c:data:`PyExc_BaseException`           | :exc:`BaseException`            | \(1)     |
821+-----------------------------------------+---------------------------------+----------+
822| :c:data:`PyExc_Exception`               | :exc:`Exception`                | \(1)     |
823+-----------------------------------------+---------------------------------+----------+
824| :c:data:`PyExc_ArithmeticError`         | :exc:`ArithmeticError`          | \(1)     |
825+-----------------------------------------+---------------------------------+----------+
826| :c:data:`PyExc_AssertionError`          | :exc:`AssertionError`           |          |
827+-----------------------------------------+---------------------------------+----------+
828| :c:data:`PyExc_AttributeError`          | :exc:`AttributeError`           |          |
829+-----------------------------------------+---------------------------------+----------+
830| :c:data:`PyExc_BlockingIOError`         | :exc:`BlockingIOError`          |          |
831+-----------------------------------------+---------------------------------+----------+
832| :c:data:`PyExc_BrokenPipeError`         | :exc:`BrokenPipeError`          |          |
833+-----------------------------------------+---------------------------------+----------+
834| :c:data:`PyExc_BufferError`             | :exc:`BufferError`              |          |
835+-----------------------------------------+---------------------------------+----------+
836| :c:data:`PyExc_ChildProcessError`       | :exc:`ChildProcessError`        |          |
837+-----------------------------------------+---------------------------------+----------+
838| :c:data:`PyExc_ConnectionAbortedError`  | :exc:`ConnectionAbortedError`   |          |
839+-----------------------------------------+---------------------------------+----------+
840| :c:data:`PyExc_ConnectionError`         | :exc:`ConnectionError`          |          |
841+-----------------------------------------+---------------------------------+----------+
842| :c:data:`PyExc_ConnectionRefusedError`  | :exc:`ConnectionRefusedError`   |          |
843+-----------------------------------------+---------------------------------+----------+
844| :c:data:`PyExc_ConnectionResetError`    | :exc:`ConnectionResetError`     |          |
845+-----------------------------------------+---------------------------------+----------+
846| :c:data:`PyExc_EOFError`                | :exc:`EOFError`                 |          |
847+-----------------------------------------+---------------------------------+----------+
848| :c:data:`PyExc_FileExistsError`         | :exc:`FileExistsError`          |          |
849+-----------------------------------------+---------------------------------+----------+
850| :c:data:`PyExc_FileNotFoundError`       | :exc:`FileNotFoundError`        |          |
851+-----------------------------------------+---------------------------------+----------+
852| :c:data:`PyExc_FloatingPointError`      | :exc:`FloatingPointError`       |          |
853+-----------------------------------------+---------------------------------+----------+
854| :c:data:`PyExc_GeneratorExit`           | :exc:`GeneratorExit`            |          |
855+-----------------------------------------+---------------------------------+----------+
856| :c:data:`PyExc_ImportError`             | :exc:`ImportError`              |          |
857+-----------------------------------------+---------------------------------+----------+
858| :c:data:`PyExc_IndentationError`        | :exc:`IndentationError`         |          |
859+-----------------------------------------+---------------------------------+----------+
860| :c:data:`PyExc_IndexError`              | :exc:`IndexError`               |          |
861+-----------------------------------------+---------------------------------+----------+
862| :c:data:`PyExc_InterruptedError`        | :exc:`InterruptedError`         |          |
863+-----------------------------------------+---------------------------------+----------+
864| :c:data:`PyExc_IsADirectoryError`       | :exc:`IsADirectoryError`        |          |
865+-----------------------------------------+---------------------------------+----------+
866| :c:data:`PyExc_KeyError`                | :exc:`KeyError`                 |          |
867+-----------------------------------------+---------------------------------+----------+
868| :c:data:`PyExc_KeyboardInterrupt`       | :exc:`KeyboardInterrupt`        |          |
869+-----------------------------------------+---------------------------------+----------+
870| :c:data:`PyExc_LookupError`             | :exc:`LookupError`              | \(1)     |
871+-----------------------------------------+---------------------------------+----------+
872| :c:data:`PyExc_MemoryError`             | :exc:`MemoryError`              |          |
873+-----------------------------------------+---------------------------------+----------+
874| :c:data:`PyExc_ModuleNotFoundError`     | :exc:`ModuleNotFoundError`      |          |
875+-----------------------------------------+---------------------------------+----------+
876| :c:data:`PyExc_NameError`               | :exc:`NameError`                |          |
877+-----------------------------------------+---------------------------------+----------+
878| :c:data:`PyExc_NotADirectoryError`      | :exc:`NotADirectoryError`       |          |
879+-----------------------------------------+---------------------------------+----------+
880| :c:data:`PyExc_NotImplementedError`     | :exc:`NotImplementedError`      |          |
881+-----------------------------------------+---------------------------------+----------+
882| :c:data:`PyExc_OSError`                 | :exc:`OSError`                  | \(1)     |
883+-----------------------------------------+---------------------------------+----------+
884| :c:data:`PyExc_OverflowError`           | :exc:`OverflowError`            |          |
885+-----------------------------------------+---------------------------------+----------+
886| :c:data:`PyExc_PermissionError`         | :exc:`PermissionError`          |          |
887+-----------------------------------------+---------------------------------+----------+
888| :c:data:`PyExc_ProcessLookupError`      | :exc:`ProcessLookupError`       |          |
889+-----------------------------------------+---------------------------------+----------+
890| :c:data:`PyExc_RecursionError`          | :exc:`RecursionError`           |          |
891+-----------------------------------------+---------------------------------+----------+
892| :c:data:`PyExc_ReferenceError`          | :exc:`ReferenceError`           | \(2)     |
893+-----------------------------------------+---------------------------------+----------+
894| :c:data:`PyExc_RuntimeError`            | :exc:`RuntimeError`             |          |
895+-----------------------------------------+---------------------------------+----------+
896| :c:data:`PyExc_StopAsyncIteration`      | :exc:`StopAsyncIteration`       |          |
897+-----------------------------------------+---------------------------------+----------+
898| :c:data:`PyExc_StopIteration`           | :exc:`StopIteration`            |          |
899+-----------------------------------------+---------------------------------+----------+
900| :c:data:`PyExc_SyntaxError`             | :exc:`SyntaxError`              |          |
901+-----------------------------------------+---------------------------------+----------+
902| :c:data:`PyExc_SystemError`             | :exc:`SystemError`              |          |
903+-----------------------------------------+---------------------------------+----------+
904| :c:data:`PyExc_SystemExit`              | :exc:`SystemExit`               |          |
905+-----------------------------------------+---------------------------------+----------+
906| :c:data:`PyExc_TabError`                | :exc:`TabError`                 |          |
907+-----------------------------------------+---------------------------------+----------+
908| :c:data:`PyExc_TimeoutError`            | :exc:`TimeoutError`             |          |
909+-----------------------------------------+---------------------------------+----------+
910| :c:data:`PyExc_TypeError`               | :exc:`TypeError`                |          |
911+-----------------------------------------+---------------------------------+----------+
912| :c:data:`PyExc_UnboundLocalError`       | :exc:`UnboundLocalError`        |          |
913+-----------------------------------------+---------------------------------+----------+
914| :c:data:`PyExc_UnicodeDecodeError`      | :exc:`UnicodeDecodeError`       |          |
915+-----------------------------------------+---------------------------------+----------+
916| :c:data:`PyExc_UnicodeEncodeError`      | :exc:`UnicodeEncodeError`       |          |
917+-----------------------------------------+---------------------------------+----------+
918| :c:data:`PyExc_UnicodeError`            | :exc:`UnicodeError`             |          |
919+-----------------------------------------+---------------------------------+----------+
920| :c:data:`PyExc_UnicodeTranslateError`   | :exc:`UnicodeTranslateError`    |          |
921+-----------------------------------------+---------------------------------+----------+
922| :c:data:`PyExc_ValueError`              | :exc:`ValueError`               |          |
923+-----------------------------------------+---------------------------------+----------+
924| :c:data:`PyExc_ZeroDivisionError`       | :exc:`ZeroDivisionError`        |          |
925+-----------------------------------------+---------------------------------+----------+
926
927.. versionadded:: 3.3
928   :c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`,
929   :c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`,
930   :c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`,
931   :c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`,
932   :c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`,
933   :c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`,
934   :c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError`
935   and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`.
936
937.. versionadded:: 3.5
938   :c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`.
939
940.. versionadded:: 3.6
941   :c:data:`PyExc_ModuleNotFoundError`.
942
943These are compatibility aliases to :c:data:`PyExc_OSError`:
944
945.. index::
946   single: PyExc_EnvironmentError
947   single: PyExc_IOError
948   single: PyExc_WindowsError
949
950+-------------------------------------+----------+
951| C Name                              | Notes    |
952+=====================================+==========+
953| :c:data:`PyExc_EnvironmentError`    |          |
954+-------------------------------------+----------+
955| :c:data:`PyExc_IOError`             |          |
956+-------------------------------------+----------+
957| :c:data:`PyExc_WindowsError`        | \(3)     |
958+-------------------------------------+----------+
959
960.. versionchanged:: 3.3
961   These aliases used to be separate exception types.
962
963Notes:
964
965(1)
966   This is a base class for other standard exceptions.
967
968(2)
969   This is the same as :exc:`weakref.ReferenceError`.
970
971(3)
972   Only defined on Windows; protect code that uses this by testing that the
973   preprocessor macro ``MS_WINDOWS`` is defined.
974
975.. _standardwarningcategories:
976
977Standard Warning Categories
978===========================
979
980All standard Python warning categories are available as global variables whose
981names are ``PyExc_`` followed by the Python exception name. These have the type
982:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
983the variables:
984
985.. index::
986   single: PyExc_Warning
987   single: PyExc_BytesWarning
988   single: PyExc_DeprecationWarning
989   single: PyExc_FutureWarning
990   single: PyExc_ImportWarning
991   single: PyExc_PendingDeprecationWarning
992   single: PyExc_ResourceWarning
993   single: PyExc_RuntimeWarning
994   single: PyExc_SyntaxWarning
995   single: PyExc_UnicodeWarning
996   single: PyExc_UserWarning
997
998+------------------------------------------+---------------------------------+----------+
999| C Name                                   | Python Name                     | Notes    |
1000+==========================================+=================================+==========+
1001| :c:data:`PyExc_Warning`                  | :exc:`Warning`                  | \(1)     |
1002+------------------------------------------+---------------------------------+----------+
1003| :c:data:`PyExc_BytesWarning`             | :exc:`BytesWarning`             |          |
1004+------------------------------------------+---------------------------------+----------+
1005| :c:data:`PyExc_DeprecationWarning`       | :exc:`DeprecationWarning`       |          |
1006+------------------------------------------+---------------------------------+----------+
1007| :c:data:`PyExc_FutureWarning`            | :exc:`FutureWarning`            |          |
1008+------------------------------------------+---------------------------------+----------+
1009| :c:data:`PyExc_ImportWarning`            | :exc:`ImportWarning`            |          |
1010+------------------------------------------+---------------------------------+----------+
1011| :c:data:`PyExc_PendingDeprecationWarning`| :exc:`PendingDeprecationWarning`|          |
1012+------------------------------------------+---------------------------------+----------+
1013| :c:data:`PyExc_ResourceWarning`          | :exc:`ResourceWarning`          |          |
1014+------------------------------------------+---------------------------------+----------+
1015| :c:data:`PyExc_RuntimeWarning`           | :exc:`RuntimeWarning`           |          |
1016+------------------------------------------+---------------------------------+----------+
1017| :c:data:`PyExc_SyntaxWarning`            | :exc:`SyntaxWarning`            |          |
1018+------------------------------------------+---------------------------------+----------+
1019| :c:data:`PyExc_UnicodeWarning`           | :exc:`UnicodeWarning`           |          |
1020+------------------------------------------+---------------------------------+----------+
1021| :c:data:`PyExc_UserWarning`              | :exc:`UserWarning`              |          |
1022+------------------------------------------+---------------------------------+----------+
1023
1024.. versionadded:: 3.2
1025   :c:data:`PyExc_ResourceWarning`.
1026
1027Notes:
1028
1029(1)
1030   This is a base class for other standard warning categories.
1031