| 1 |
.. highlight:: 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 ``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 |
**Unless** the error is a ``SystemExit``, in that case no traceback is |
| 57 |
printed and the Python process will exit with the error code specified by |
| 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 variable :data:`sys.last_exc` is |
| 64 |
set to the printed exception. For backwards compatibility, the |
| 65 |
deprecated variables :data:`sys.last_type`, :data:`sys.last_value` and |
| 66 |
:data:`sys.last_traceback` are also set to the type, value and traceback |
| 67 |
of this exception, respectively. |
| 68 |
|
| 69 |
.. versionchanged:: 3.12 |
| 70 |
The setting of :data:`sys.last_exc` was added. |
| 71 |
|
| 72 |
|
| 73 |
.. c:function:: void PyErr_Print() |
| 74 |
|
| 75 |
Alias for ``PyErr_PrintEx(1)``. |
| 76 |
|
| 77 |
|
| 78 |
.. c:function:: void PyErr_WriteUnraisable(PyObject *obj) |
| 79 |
|
| 80 |
Call :func:`sys.unraisablehook` using the current exception and *obj* |
| 81 |
argument. |
| 82 |
|
| 83 |
This utility function prints a warning message to ``sys.stderr`` when an |
| 84 |
exception has been set but it is impossible for the interpreter to actually |
| 85 |
raise the exception. It is used, for example, when an exception occurs in an |
| 86 |
:meth:`~object.__del__` method. |
| 87 |
|
| 88 |
The function is called with a single argument *obj* that identifies the context |
| 89 |
in which the unraisable exception occurred. If possible, |
| 90 |
the repr of *obj* will be printed in the warning message. |
| 91 |
If *obj* is ``NULL``, only the traceback is printed. |
| 92 |
|
| 93 |
An exception must be set when calling this function. |
| 94 |
|
| 95 |
.. versionchanged:: 3.4 |
| 96 |
Print a traceback. Print only traceback if *obj* is ``NULL``. |
| 97 |
|
| 98 |
.. versionchanged:: 3.8 |
| 99 |
Use :func:`sys.unraisablehook`. |
| 100 |
|
| 101 |
|
| 102 |
.. c:function:: void PyErr_FormatUnraisable(const char *format, ...) |
| 103 |
|
| 104 |
Similar to :c:func:`PyErr_WriteUnraisable`, but the *format* and subsequent |
| 105 |
parameters help format the warning message; they have the same meaning and |
| 106 |
values as in :c:func:`PyUnicode_FromFormat`. |
| 107 |
``PyErr_WriteUnraisable(obj)`` is roughly equivalent to |
| 108 |
``PyErr_FormatUnraisable("Exception ignored in: %R", obj)``. |
| 109 |
If *format* is ``NULL``, only the traceback is printed. |
| 110 |
|
| 111 |
.. versionadded:: 3.13 |
| 112 |
|
| 113 |
|
| 114 |
.. c:function:: void PyErr_DisplayException(PyObject *exc) |
| 115 |
|
| 116 |
Print the standard traceback display of ``exc`` to ``sys.stderr``, including |
| 117 |
chained exceptions and notes. |
| 118 |
|
| 119 |
.. versionadded:: 3.12 |
| 120 |
|
| 121 |
|
| 122 |
Raising exceptions |
| 123 |
================== |
| 124 |
|
| 125 |
These functions help you set the current thread's error indicator. |
| 126 |
For convenience, some of these functions will always return a |
| 127 |
``NULL`` pointer for use in a ``return`` statement. |
| 128 |
|
| 129 |
|
| 130 |
.. c:function:: void PyErr_SetString(PyObject *type, const char *message) |
| 131 |
|
| 132 |
This is the most common way to set the error indicator. The first argument |
| 133 |
specifies the exception type; it is normally one of the standard exceptions, |
| 134 |
e.g. :c:data:`PyExc_RuntimeError`. You need not create a new |
| 135 |
:term:`strong reference` to it (e.g. with :c:func:`Py_INCREF`). |
| 136 |
The second argument is an error message; it is decoded from ``'utf-8'``. |
| 137 |
|
| 138 |
|
| 139 |
.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value) |
| 140 |
|
| 141 |
This function is similar to :c:func:`PyErr_SetString` but lets you specify an |
| 142 |
arbitrary Python object for the "value" of the exception. |
| 143 |
|
| 144 |
|
| 145 |
.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...) |
| 146 |
|
| 147 |
This function sets the error indicator and returns ``NULL``. *exception* |
| 148 |
should be a Python exception class. The *format* and subsequent |
| 149 |
parameters help format the error message; they have the same meaning and |
| 150 |
values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded |
| 151 |
string. |
| 152 |
|
| 153 |
|
| 154 |
.. c:function:: PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs) |
| 155 |
|
| 156 |
Same as :c:func:`PyErr_Format`, but taking a :c:type:`va_list` argument rather |
| 157 |
than a variable number of arguments. |
| 158 |
|
| 159 |
.. versionadded:: 3.5 |
| 160 |
|
| 161 |
|
| 162 |
.. c:function:: void PyErr_SetNone(PyObject *type) |
| 163 |
|
| 164 |
This is a shorthand for ``PyErr_SetObject(type, Py_None)``. |
| 165 |
|
| 166 |
|
| 167 |
.. c:function:: int PyErr_BadArgument() |
| 168 |
|
| 169 |
This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where |
| 170 |
*message* indicates that a built-in operation was invoked with an illegal |
| 171 |
argument. It is mostly for internal use. |
| 172 |
|
| 173 |
|
| 174 |
.. c:function:: PyObject* PyErr_NoMemory() |
| 175 |
|
| 176 |
This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns ``NULL`` |
| 177 |
so an object allocation function can write ``return PyErr_NoMemory();`` when it |
| 178 |
runs out of memory. |
| 179 |
|
| 180 |
|
| 181 |
.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type) |
| 182 |
|
| 183 |
.. index:: single: strerror (C function) |
| 184 |
|
| 185 |
This is a convenience function to raise an exception when a C library function |
| 186 |
has returned an error and set the C variable :c:data:`errno`. It constructs a |
| 187 |
tuple object whose first item is the integer :c:data:`errno` value and whose |
| 188 |
second item is the corresponding error message (gotten from :c:func:`!strerror`), |
| 189 |
and then calls ``PyErr_SetObject(type, object)``. On Unix, when the |
| 190 |
:c:data:`errno` value is :c:macro:`!EINTR`, indicating an interrupted system call, |
| 191 |
this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator, |
| 192 |
leaves it set to that. The function always returns ``NULL``, so a wrapper |
| 193 |
function around a system call can write ``return PyErr_SetFromErrno(type);`` |
| 194 |
when the system call returns an error. |
| 195 |
|
| 196 |
|
| 197 |
.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject) |
| 198 |
|
| 199 |
Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if |
| 200 |
*filenameObject* is not ``NULL``, it is passed to the constructor of *type* as |
| 201 |
a third parameter. In the case of :exc:`OSError` exception, |
| 202 |
this is used to define the :attr:`!filename` attribute of the |
| 203 |
exception instance. |
| 204 |
|
| 205 |
|
| 206 |
.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2) |
| 207 |
|
| 208 |
Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but takes a second |
| 209 |
filename object, for raising errors when a function that takes two filenames |
| 210 |
fails. |
| 211 |
|
| 212 |
.. versionadded:: 3.4 |
| 213 |
|
| 214 |
|
| 215 |
.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename) |
| 216 |
|
| 217 |
Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename |
| 218 |
is given as a C string. *filename* is decoded from the :term:`filesystem |
| 219 |
encoding and error handler`. |
| 220 |
|
| 221 |
|
| 222 |
.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr) |
| 223 |
|
| 224 |
This is a convenience function to raise :exc:`OSError`. If called with |
| 225 |
*ierr* of ``0``, the error code returned by a call to :c:func:`!GetLastError` |
| 226 |
is used instead. It calls the Win32 function :c:func:`!FormatMessage` to retrieve |
| 227 |
the Windows description of error code given by *ierr* or :c:func:`!GetLastError`, |
| 228 |
then it constructs a :exc:`OSError` object with the :attr:`~OSError.winerror` |
| 229 |
attribute set to the error code, the :attr:`~OSError.strerror` attribute |
| 230 |
set to the corresponding error message (gotten from |
| 231 |
:c:func:`!FormatMessage`), and then calls ``PyErr_SetObject(PyExc_OSError, |
| 232 |
object)``. This function always returns ``NULL``. |
| 233 |
|
| 234 |
.. availability:: Windows. |
| 235 |
|
| 236 |
|
| 237 |
.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr) |
| 238 |
|
| 239 |
Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter |
| 240 |
specifying the exception type to be raised. |
| 241 |
|
| 242 |
.. availability:: Windows. |
| 243 |
|
| 244 |
|
| 245 |
.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) |
| 246 |
|
| 247 |
Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior |
| 248 |
that if *filename* is not ``NULL``, it is decoded from the filesystem |
| 249 |
encoding (:func:`os.fsdecode`) and passed to the constructor of |
| 250 |
:exc:`OSError` as a third parameter to be used to define the |
| 251 |
:attr:`!filename` attribute of the exception instance. |
| 252 |
|
| 253 |
.. availability:: Windows. |
| 254 |
|
| 255 |
|
| 256 |
.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename) |
| 257 |
|
| 258 |
Similar to :c:func:`PyErr_SetExcFromWindowsErr`, with the additional behavior |
| 259 |
that if *filename* is not ``NULL``, it is passed to the constructor of |
| 260 |
:exc:`OSError` as a third parameter to be used to define the |
| 261 |
:attr:`!filename` attribute of the exception instance. |
| 262 |
|
| 263 |
.. availability:: Windows. |
| 264 |
|
| 265 |
|
| 266 |
.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2) |
| 267 |
|
| 268 |
Similar to :c:func:`PyErr_SetExcFromWindowsErrWithFilenameObject`, |
| 269 |
but accepts a second filename object. |
| 270 |
|
| 271 |
.. availability:: Windows. |
| 272 |
|
| 273 |
.. versionadded:: 3.4 |
| 274 |
|
| 275 |
|
| 276 |
.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename) |
| 277 |
|
| 278 |
Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional |
| 279 |
parameter specifying the exception type to be raised. |
| 280 |
|
| 281 |
.. availability:: Windows. |
| 282 |
|
| 283 |
|
| 284 |
.. c:function:: PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path) |
| 285 |
|
| 286 |
This is a convenience function to raise :exc:`ImportError`. *msg* will be |
| 287 |
set as the exception's message string. *name* and *path*, both of which can |
| 288 |
be ``NULL``, will be set as the :exc:`ImportError`'s respective ``name`` |
| 289 |
and ``path`` attributes. |
| 290 |
|
| 291 |
.. versionadded:: 3.3 |
| 292 |
|
| 293 |
|
| 294 |
.. c:function:: PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path) |
| 295 |
|
| 296 |
Much like :c:func:`PyErr_SetImportError` but this function allows for |
| 297 |
specifying a subclass of :exc:`ImportError` to raise. |
| 298 |
|
| 299 |
.. versionadded:: 3.6 |
| 300 |
|
| 301 |
|
| 302 |
.. c:function:: void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) |
| 303 |
|
| 304 |
Set file, line, and offset information for the current exception. If the |
| 305 |
current exception is not a :exc:`SyntaxError`, then it sets additional |
| 306 |
attributes, which make the exception printing subsystem think the exception |
| 307 |
is a :exc:`SyntaxError`. |
| 308 |
|
| 309 |
.. versionadded:: 3.4 |
| 310 |
|
| 311 |
|
| 312 |
.. c:function:: void PyErr_RangedSyntaxLocationObject(PyObject *filename, int lineno, int col_offset, int end_lineno, int end_col_offset) |
| 313 |
|
| 314 |
Similar to :c:func:`PyErr_SyntaxLocationObject`, but also sets the |
| 315 |
*end_lineno* and *end_col_offset* information for the current exception. |
| 316 |
|
| 317 |
.. versionadded:: 3.10 |
| 318 |
|
| 319 |
|
| 320 |
.. c:function:: void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset) |
| 321 |
|
| 322 |
Like :c:func:`PyErr_SyntaxLocationObject`, but *filename* is a byte string |
| 323 |
decoded from the :term:`filesystem encoding and error handler`. |
| 324 |
|
| 325 |
.. versionadded:: 3.2 |
| 326 |
|
| 327 |
|
| 328 |
.. c:function:: void PyErr_SyntaxLocation(const char *filename, int lineno) |
| 329 |
|
| 330 |
Like :c:func:`PyErr_SyntaxLocationEx`, but the *col_offset* parameter is |
| 331 |
omitted. |
| 332 |
|
| 333 |
|
| 334 |
.. c:function:: void PyErr_BadInternalCall() |
| 335 |
|
| 336 |
This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``, |
| 337 |
where *message* indicates that an internal operation (e.g. a Python/C API |
| 338 |
function) was invoked with an illegal argument. It is mostly for internal |
| 339 |
use. |
| 340 |
|
| 341 |
|
| 342 |
.. c:function:: PyObject *PyErr_ProgramTextObject(PyObject *filename, int lineno) |
| 343 |
|
| 344 |
Get the source line in *filename* at line *lineno*. *filename* should be a |
| 345 |
Python :class:`str` object. |
| 346 |
|
| 347 |
On success, this function returns a Python string object with the found line. |
| 348 |
On failure, this function returns ``NULL`` without an exception set. |
| 349 |
|
| 350 |
|
| 351 |
.. c:function:: PyObject *PyErr_ProgramText(const char *filename, int lineno) |
| 352 |
|
| 353 |
Similar to :c:func:`PyErr_ProgramTextObject`, but *filename* is a |
| 354 |
:c:expr:`const char *`, which is decoded with the |
| 355 |
:term:`filesystem encoding and error handler`, instead of a |
| 356 |
Python object reference. |
| 357 |
|
| 358 |
|
| 359 |
Issuing warnings |
| 360 |
================ |
| 361 |
|
| 362 |
Use these functions to issue warnings from C code. They mirror similar |
| 363 |
functions exported by the Python :mod:`warnings` module. They normally |
| 364 |
print a warning message to *sys.stderr*; however, it is |
| 365 |
also possible that the user has specified that warnings are to be turned into |
| 366 |
errors, and in that case they will raise an exception. It is also possible that |
| 367 |
the functions raise an exception because of a problem with the warning machinery. |
| 368 |
The return value is ``0`` if no exception is raised, or ``-1`` if an exception |
| 369 |
is raised. (It is not possible to determine whether a warning message is |
| 370 |
actually printed, nor what the reason is for the exception; this is |
| 371 |
intentional.) If an exception is raised, the caller should do its normal |
| 372 |
exception handling (for example, :c:func:`Py_DECREF` owned references and return |
| 373 |
an error value). |
| 374 |
|
| 375 |
.. c:function:: int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level) |
| 376 |
|
| 377 |
Issue a warning message. The *category* argument is a warning category (see |
| 378 |
below) or ``NULL``; the *message* argument is a UTF-8 encoded string. *stack_level* is a |
| 379 |
positive number giving a number of stack frames; the warning will be issued from |
| 380 |
the currently executing line of code in that stack frame. A *stack_level* of 1 |
| 381 |
is the function calling :c:func:`PyErr_WarnEx`, 2 is the function above that, |
| 382 |
and so forth. |
| 383 |
|
| 384 |
Warning categories must be subclasses of :c:data:`PyExc_Warning`; |
| 385 |
:c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`; |
| 386 |
the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard |
| 387 |
Python warning categories are available as global variables whose names are |
| 388 |
enumerated at :ref:`standardwarningcategories`. |
| 389 |
|
| 390 |
For information about warning control, see the documentation for the |
| 391 |
:mod:`warnings` module and the :option:`-W` option in the command line |
| 392 |
documentation. There is no C API for warning control. |
| 393 |
|
| 394 |
|
| 395 |
.. c:function:: int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry) |
| 396 |
|
| 397 |
Issue a warning message with explicit control over all warning attributes. This |
| 398 |
is a straightforward wrapper around the Python function |
| 399 |
:func:`warnings.warn_explicit`; see there for more information. The *module* |
| 400 |
and *registry* arguments may be set to ``NULL`` to get the default effect |
| 401 |
described there. |
| 402 |
|
| 403 |
.. versionadded:: 3.4 |
| 404 |
|
| 405 |
|
| 406 |
.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry) |
| 407 |
|
| 408 |
Similar to :c:func:`PyErr_WarnExplicitObject` except that *message* and |
| 409 |
*module* are UTF-8 encoded strings, and *filename* is decoded from the |
| 410 |
:term:`filesystem encoding and error handler`. |
| 411 |
|
| 412 |
|
| 413 |
.. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...) |
| 414 |
|
| 415 |
Function similar to :c:func:`PyErr_WarnEx`, but use |
| 416 |
:c:func:`PyUnicode_FromFormat` to format the warning message. *format* is |
| 417 |
an ASCII-encoded string. |
| 418 |
|
| 419 |
.. versionadded:: 3.2 |
| 420 |
|
| 421 |
|
| 422 |
.. c:function:: int PyErr_WarnExplicitFormat(PyObject *category, const char *filename, int lineno, const char *module, PyObject *registry, const char *format, ...) |
| 423 |
|
| 424 |
Similar to :c:func:`PyErr_WarnExplicit`, but uses |
| 425 |
:c:func:`PyUnicode_FromFormat` to format the warning message. *format* is |
| 426 |
an ASCII-encoded string. |
| 427 |
|
| 428 |
.. versionadded:: 3.2 |
| 429 |
|
| 430 |
|
| 431 |
.. c:function:: int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...) |
| 432 |
|
| 433 |
Function similar to :c:func:`PyErr_WarnFormat`, but *category* is |
| 434 |
:exc:`ResourceWarning` and it passes *source* to :class:`!warnings.WarningMessage`. |
| 435 |
|
| 436 |
.. versionadded:: 3.6 |
| 437 |
|
| 438 |
|
| 439 |
Querying the error indicator |
| 440 |
============================ |
| 441 |
|
| 442 |
.. c:function:: PyObject* PyErr_Occurred() |
| 443 |
|
| 444 |
Test whether the error indicator is set. If set, return the exception *type* |
| 445 |
(the first argument to the last call to one of the ``PyErr_Set*`` |
| 446 |
functions or to :c:func:`PyErr_Restore`). If not set, return ``NULL``. You do not |
| 447 |
own a reference to the return value, so you do not need to :c:func:`Py_DECREF` |
| 448 |
it. |
| 449 |
|
| 450 |
The caller must have an :term:`attached thread state`. |
| 451 |
|
| 452 |
.. note:: |
| 453 |
|
| 454 |
Do not compare the return value to a specific exception; use |
| 455 |
:c:func:`PyErr_ExceptionMatches` instead, shown below. (The comparison could |
| 456 |
easily fail since the exception may be an instance instead of a class, in the |
| 457 |
case of a class exception, or it may be a subclass of the expected exception.) |
| 458 |
|
| 459 |
|
| 460 |
.. c:function:: int PyErr_ExceptionMatches(PyObject *exc) |
| 461 |
|
| 462 |
Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``. This |
| 463 |
should only be called when an exception is actually set; a memory access |
| 464 |
violation will occur if no exception has been raised. |
| 465 |
|
| 466 |
|
| 467 |
.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc) |
| 468 |
|
| 469 |
Return true if the *given* exception matches the exception type in *exc*. If |
| 470 |
*exc* is a class object, this also returns true when *given* is an instance |
| 471 |
of a subclass. If *exc* is a tuple, all exception types in the tuple (and |
| 472 |
recursively in subtuples) are searched for a match. |
| 473 |
|
| 474 |
|
| 475 |
.. c:function:: PyObject *PyErr_GetRaisedException(void) |
| 476 |
|
| 477 |
Return the exception currently being raised, clearing the error indicator at |
| 478 |
the same time. Return ``NULL`` if the error indicator is not set. |
| 479 |
|
| 480 |
This function is used by code that needs to catch exceptions, |
| 481 |
or code that needs to save and restore the error indicator temporarily. |
| 482 |
|
| 483 |
For example:: |
| 484 |
|
| 485 |
{ |
| 486 |
PyObject *exc = PyErr_GetRaisedException(); |
| 487 |
|
| 488 |
/* ... code that might produce other errors ... */ |
| 489 |
|
| 490 |
PyErr_SetRaisedException(exc); |
| 491 |
} |
| 492 |
|
| 493 |
.. seealso:: :c:func:`PyErr_GetHandledException`, |
| 494 |
to save the exception currently being handled. |
| 495 |
|
| 496 |
.. versionadded:: 3.12 |
| 497 |
|
| 498 |
|
| 499 |
.. c:function:: void PyErr_SetRaisedException(PyObject *exc) |
| 500 |
|
| 501 |
Set *exc* as the exception currently being raised, |
| 502 |
clearing the existing exception if one is set. |
| 503 |
|
| 504 |
.. warning:: |
| 505 |
|
| 506 |
This call steals a reference to *exc*, which must be a valid exception. |
| 507 |
|
| 508 |
.. versionadded:: 3.12 |
| 509 |
|
| 510 |
|
| 511 |
.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) |
| 512 |
|
| 513 |
.. deprecated:: 3.12 |
| 514 |
|
| 515 |
Use :c:func:`PyErr_GetRaisedException` instead. |
| 516 |
|
| 517 |
Retrieve the error indicator into three variables whose addresses are passed. |
| 518 |
If the error indicator is not set, set all three variables to ``NULL``. If it is |
| 519 |
set, it will be cleared and you own a reference to each object retrieved. The |
| 520 |
value and traceback object may be ``NULL`` even when the type object is not. |
| 521 |
|
| 522 |
.. note:: |
| 523 |
|
| 524 |
This function is normally only used by legacy code that needs to catch |
| 525 |
exceptions or save and restore the error indicator temporarily. |
| 526 |
|
| 527 |
For example:: |
| 528 |
|
| 529 |
{ |
| 530 |
PyObject *type, *value, *traceback; |
| 531 |
PyErr_Fetch(&type, &value, &traceback); |
| 532 |
|
| 533 |
/* ... code that might produce other errors ... */ |
| 534 |
|
| 535 |
PyErr_Restore(type, value, traceback); |
| 536 |
} |
| 537 |
|
| 538 |
|
| 539 |
.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) |
| 540 |
|
| 541 |
.. deprecated:: 3.12 |
| 542 |
|
| 543 |
Use :c:func:`PyErr_SetRaisedException` instead. |
| 544 |
|
| 545 |
Set the error indicator from the three objects, |
| 546 |
*type*, *value*, and *traceback*, |
| 547 |
clearing the existing exception if one is set. |
| 548 |
If the objects are ``NULL``, the error |
| 549 |
indicator is cleared. Do not pass a ``NULL`` type and non-``NULL`` value or |
| 550 |
traceback. The exception type should be a class. Do not pass an invalid |
| 551 |
exception type or value. (Violating these rules will cause subtle problems |
| 552 |
later.) This call takes away a reference to each object: you must own a |
| 553 |
reference to each object before the call and after the call you no longer own |
| 554 |
these references. (If you don't understand this, don't use this function. I |
| 555 |
warned you.) |
| 556 |
|
| 557 |
.. note:: |
| 558 |
|
| 559 |
This function is normally only used by legacy code that needs to |
| 560 |
save and restore the error indicator temporarily. |
| 561 |
Use :c:func:`PyErr_Fetch` to save the current error indicator. |
| 562 |
|
| 563 |
|
| 564 |
.. c:function:: void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb) |
| 565 |
|
| 566 |
.. deprecated:: 3.12 |
| 567 |
|
| 568 |
Use :c:func:`PyErr_GetRaisedException` instead, |
| 569 |
to avoid any possible de-normalization. |
| 570 |
|
| 571 |
Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below |
| 572 |
can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is |
| 573 |
not an instance of the same class. This function can be used to instantiate |
| 574 |
the class in that case. If the values are already normalized, nothing happens. |
| 575 |
The delayed normalization is implemented to improve performance. |
| 576 |
|
| 577 |
.. note:: |
| 578 |
|
| 579 |
This function *does not* implicitly set the |
| 580 |
:attr:`~BaseException.__traceback__` |
| 581 |
attribute on the exception value. If setting the traceback |
| 582 |
appropriately is desired, the following additional snippet is needed:: |
| 583 |
|
| 584 |
if (tb != NULL) { |
| 585 |
PyException_SetTraceback(val, tb); |
| 586 |
} |
| 587 |
|
| 588 |
|
| 589 |
.. c:function:: PyObject* PyErr_GetHandledException(void) |
| 590 |
|
| 591 |
Retrieve the active exception instance, as would be returned by :func:`sys.exception`. |
| 592 |
This refers to an exception that was *already caught*, not to an exception that was |
| 593 |
freshly raised. Returns a new reference to the exception or ``NULL``. |
| 594 |
Does not modify the interpreter's exception state. |
| 595 |
|
| 596 |
.. note:: |
| 597 |
|
| 598 |
This function is not normally used by code that wants to handle exceptions. |
| 599 |
Rather, it can be used when code needs to save and restore the exception |
| 600 |
state temporarily. Use :c:func:`PyErr_SetHandledException` to restore or |
| 601 |
clear the exception state. |
| 602 |
|
| 603 |
.. versionadded:: 3.11 |
| 604 |
|
| 605 |
.. c:function:: void PyErr_SetHandledException(PyObject *exc) |
| 606 |
|
| 607 |
Set the active exception, as known from ``sys.exception()``. This refers |
| 608 |
to an exception that was *already caught*, not to an exception that was |
| 609 |
freshly raised. |
| 610 |
To clear the exception state, pass ``NULL``. |
| 611 |
|
| 612 |
.. note:: |
| 613 |
|
| 614 |
This function is not normally used by code that wants to handle exceptions. |
| 615 |
Rather, it can be used when code needs to save and restore the exception |
| 616 |
state temporarily. Use :c:func:`PyErr_GetHandledException` to get the exception |
| 617 |
state. |
| 618 |
|
| 619 |
.. versionadded:: 3.11 |
| 620 |
|
| 621 |
.. c:function:: void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback) |
| 622 |
|
| 623 |
Retrieve the old-style representation of the exception info, as known from |
| 624 |
:func:`sys.exc_info`. This refers to an exception that was *already caught*, |
| 625 |
not to an exception that was freshly raised. Returns new references for the |
| 626 |
three objects, any of which may be ``NULL``. Does not modify the exception |
| 627 |
info state. This function is kept for backwards compatibility. Prefer using |
| 628 |
:c:func:`PyErr_GetHandledException`. |
| 629 |
|
| 630 |
.. note:: |
| 631 |
|
| 632 |
This function is not normally used by code that wants to handle exceptions. |
| 633 |
Rather, it can be used when code needs to save and restore the exception |
| 634 |
state temporarily. Use :c:func:`PyErr_SetExcInfo` to restore or clear the |
| 635 |
exception state. |
| 636 |
|
| 637 |
.. versionadded:: 3.3 |
| 638 |
|
| 639 |
|
| 640 |
.. c:function:: void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback) |
| 641 |
|
| 642 |
Set the exception info, as known from ``sys.exc_info()``. This refers |
| 643 |
to an exception that was *already caught*, not to an exception that was |
| 644 |
freshly raised. This function steals the references of the arguments. |
| 645 |
To clear the exception state, pass ``NULL`` for all three arguments. |
| 646 |
This function is kept for backwards compatibility. Prefer using |
| 647 |
:c:func:`PyErr_SetHandledException`. |
| 648 |
|
| 649 |
.. note:: |
| 650 |
|
| 651 |
This function is not normally used by code that wants to handle exceptions. |
| 652 |
Rather, it can be used when code needs to save and restore the exception |
| 653 |
state temporarily. Use :c:func:`PyErr_GetExcInfo` to read the exception |
| 654 |
state. |
| 655 |
|
| 656 |
.. versionadded:: 3.3 |
| 657 |
|
| 658 |
.. versionchanged:: 3.11 |
| 659 |
The ``type`` and ``traceback`` arguments are no longer used and |
| 660 |
can be NULL. The interpreter now derives them from the exception |
| 661 |
instance (the ``value`` argument). The function still steals |
| 662 |
references of all three arguments. |
| 663 |
|
| 664 |
|
| 665 |
Signal Handling |
| 666 |
=============== |
| 667 |
|
| 668 |
|
| 669 |
.. c:function:: int PyErr_CheckSignals() |
| 670 |
|
| 671 |
.. index:: |
| 672 |
pair: module; signal |
| 673 |
single: SIGINT (C macro) |
| 674 |
single: KeyboardInterrupt (built-in exception) |
| 675 |
|
| 676 |
Handle external interruptions, such as signals or activating a debugger, |
| 677 |
whose processing has been delayed until it is safe |
| 678 |
to run Python code and/or raise exceptions. |
| 679 |
|
| 680 |
For example, pressing :kbd:`Ctrl-C` causes a terminal to send the |
| 681 |
:py:data:`signal.SIGINT` signal. |
| 682 |
This function executes the corresponding Python signal handler, which, |
| 683 |
by default, raises the :exc:`KeyboardInterrupt` exception. |
| 684 |
|
| 685 |
:c:func:`!PyErr_CheckSignals` should be called by long-running C code |
| 686 |
frequently enough so that the response appears immediate to humans. |
| 687 |
|
| 688 |
Handlers invoked by this function currently include: |
| 689 |
|
| 690 |
- Signal handlers, including Python functions registered using |
| 691 |
the :mod:`signal` module. |
| 692 |
|
| 693 |
Signal handlers are only run in the main thread of the main interpreter. |
| 694 |
|
| 695 |
(This is where the function got the name: originally, signals |
| 696 |
were the only way to interrupt the interpreter.) |
| 697 |
|
| 698 |
- Running the garbage collector, if necessary. |
| 699 |
|
| 700 |
- Executing a pending :ref:`remote debugger <remote-debugging>` script. |
| 701 |
|
| 702 |
If any handler raises an exception, immediately return ``-1`` with that |
| 703 |
exception set. |
| 704 |
Any remaining interruptions are left to be processed on the next |
| 705 |
:c:func:`PyErr_CheckSignals()` invocation, if appropriate. |
| 706 |
|
| 707 |
If all handlers finish successfully, or there are no handlers to run, |
| 708 |
return ``0``. |
| 709 |
|
| 710 |
.. versionchanged:: 3.12 |
| 711 |
This function may now invoke the garbage collector. |
| 712 |
|
| 713 |
.. versionchanged:: 3.14 |
| 714 |
This function may now execute a remote debugger script, if remote |
| 715 |
debugging is enabled. |
| 716 |
|
| 717 |
|
| 718 |
.. c:function:: void PyErr_SetInterrupt() |
| 719 |
|
| 720 |
.. index:: |
| 721 |
pair: module; signal |
| 722 |
single: SIGINT (C macro) |
| 723 |
single: KeyboardInterrupt (built-in exception) |
| 724 |
|
| 725 |
Simulate the effect of a :c:macro:`!SIGINT` signal arriving. |
| 726 |
This is equivalent to ``PyErr_SetInterruptEx(SIGINT)``. |
| 727 |
|
| 728 |
.. note:: |
| 729 |
This function is async-signal-safe. It can be called without |
| 730 |
an :term:`attached thread state` and from a C signal handler. |
| 731 |
|
| 732 |
|
| 733 |
.. c:function:: int PyErr_SetInterruptEx(int signum) |
| 734 |
|
| 735 |
.. index:: |
| 736 |
pair: module; signal |
| 737 |
single: KeyboardInterrupt (built-in exception) |
| 738 |
|
| 739 |
Simulate the effect of a signal arriving. The next time |
| 740 |
:c:func:`PyErr_CheckSignals` is called, the Python signal handler for |
| 741 |
the given signal number will be called. |
| 742 |
|
| 743 |
This function can be called by C code that sets up its own signal handling |
| 744 |
and wants Python signal handlers to be invoked as expected when an |
| 745 |
interruption is requested (for example when the user presses Ctrl-C |
| 746 |
to interrupt an operation). |
| 747 |
|
| 748 |
If the given signal isn't handled by Python (it was set to |
| 749 |
:py:const:`signal.SIG_DFL` or :py:const:`signal.SIG_IGN`), it will be ignored. |
| 750 |
|
| 751 |
If *signum* is outside of the allowed range of signal numbers, ``-1`` |
| 752 |
is returned. Otherwise, ``0`` is returned. The error indicator is |
| 753 |
never changed by this function. |
| 754 |
|
| 755 |
.. note:: |
| 756 |
This function is async-signal-safe. It can be called without |
| 757 |
an :term:`attached thread state` and from a C signal handler. |
| 758 |
|
| 759 |
.. versionadded:: 3.10 |
| 760 |
|
| 761 |
|
| 762 |
.. c:function:: int PySignal_SetWakeupFd(int fd) |
| 763 |
|
| 764 |
This utility function specifies a file descriptor to which the signal number |
| 765 |
is written as a single byte whenever a signal is received. *fd* must be |
| 766 |
non-blocking. It returns the previous such file descriptor. |
| 767 |
|
| 768 |
The value ``-1`` disables the feature; this is the initial state. |
| 769 |
This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any |
| 770 |
error checking. *fd* should be a valid file descriptor. The function should |
| 771 |
only be called from the main thread. |
| 772 |
|
| 773 |
.. versionchanged:: 3.5 |
| 774 |
On Windows, the function now also supports socket handles. |
| 775 |
|
| 776 |
|
| 777 |
Exception Classes |
| 778 |
================= |
| 779 |
|
| 780 |
.. c:function:: PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict) |
| 781 |
|
| 782 |
This utility function creates and returns a new exception class. The *name* |
| 783 |
argument must be the name of the new exception, a C string of the form |
| 784 |
``module.classname``. The *base* and *dict* arguments are normally ``NULL``. |
| 785 |
This creates a class object derived from :exc:`Exception` (accessible in C as |
| 786 |
:c:data:`PyExc_Exception`). |
| 787 |
|
| 788 |
The :attr:`~type.__module__` attribute of the new class is set to the first part (up |
| 789 |
to the last dot) of the *name* argument, and the class name is set to the last |
| 790 |
part (after the last dot). The *base* argument can be used to specify alternate |
| 791 |
base classes; it can either be only one class or a tuple of classes. The *dict* |
| 792 |
argument can be used to specify a dictionary of class variables and methods. |
| 793 |
|
| 794 |
|
| 795 |
.. c:function:: PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict) |
| 796 |
|
| 797 |
Same as :c:func:`PyErr_NewException`, except that the new exception class can |
| 798 |
easily be given a docstring: If *doc* is non-``NULL``, it will be used as the |
| 799 |
docstring for the exception class. |
| 800 |
|
| 801 |
.. versionadded:: 3.2 |
| 802 |
|
| 803 |
|
| 804 |
.. c:function:: int PyExceptionClass_Check(PyObject *ob) |
| 805 |
|
| 806 |
Return non-zero if *ob* is an exception class, zero otherwise. This function always succeeds. |
| 807 |
|
| 808 |
|
| 809 |
.. c:function:: const char *PyExceptionClass_Name(PyObject *ob) |
| 810 |
|
| 811 |
Return :c:member:`~PyTypeObject.tp_name` of the exception class *ob*. |
| 812 |
|
| 813 |
|
| 814 |
Exception Objects |
| 815 |
================= |
| 816 |
|
| 817 |
.. c:function:: int PyExceptionInstance_Check(PyObject *op) |
| 818 |
|
| 819 |
Return true if *op* is an instance of :class:`BaseException`, false |
| 820 |
otherwise. This function always succeeds. |
| 821 |
|
| 822 |
|
| 823 |
.. c:macro:: PyExceptionInstance_Class(op) |
| 824 |
|
| 825 |
Equivalent to :c:func:`Py_TYPE(op) <Py_TYPE>`. |
| 826 |
|
| 827 |
|
| 828 |
.. c:function:: PyObject* PyException_GetTraceback(PyObject *ex) |
| 829 |
|
| 830 |
Return the traceback associated with the exception as a new reference, as |
| 831 |
accessible from Python through the :attr:`~BaseException.__traceback__` |
| 832 |
attribute. If there is no |
| 833 |
traceback associated, this returns ``NULL``. |
| 834 |
|
| 835 |
|
| 836 |
.. c:function:: int PyException_SetTraceback(PyObject *ex, PyObject *tb) |
| 837 |
|
| 838 |
Set the traceback associated with the exception to *tb*. Use ``Py_None`` to |
| 839 |
clear it. |
| 840 |
|
| 841 |
|
| 842 |
.. c:function:: PyObject* PyException_GetContext(PyObject *ex) |
| 843 |
|
| 844 |
Return the context (another exception instance during whose handling *ex* was |
| 845 |
raised) associated with the exception as a new reference, as accessible from |
| 846 |
Python through the :attr:`~BaseException.__context__` attribute. |
| 847 |
If there is no context associated, this returns ``NULL``. |
| 848 |
|
| 849 |
|
| 850 |
.. c:function:: void PyException_SetContext(PyObject *ex, PyObject *ctx) |
| 851 |
|
| 852 |
Set the context associated with the exception to *ctx*. Use ``NULL`` to clear |
| 853 |
it. There is no type check to make sure that *ctx* is an exception instance. |
| 854 |
This steals a reference to *ctx*. |
| 855 |
|
| 856 |
|
| 857 |
.. c:function:: PyObject* PyException_GetCause(PyObject *ex) |
| 858 |
|
| 859 |
Return the cause (either an exception instance, or ``None``, |
| 860 |
set by ``raise ... from ...``) associated with the exception as a new |
| 861 |
reference, as accessible from Python through the |
| 862 |
:attr:`~BaseException.__cause__` attribute. |
| 863 |
|
| 864 |
|
| 865 |
.. c:function:: void PyException_SetCause(PyObject *ex, PyObject *cause) |
| 866 |
|
| 867 |
Set the cause associated with the exception to *cause*. Use ``NULL`` to clear |
| 868 |
it. There is no type check to make sure that *cause* is either an exception |
| 869 |
instance or ``None``. This steals a reference to *cause*. |
| 870 |
|
| 871 |
The :attr:`~BaseException.__suppress_context__` attribute is implicitly set |
| 872 |
to ``True`` by this function. |
| 873 |
|
| 874 |
|
| 875 |
.. c:function:: PyObject* PyException_GetArgs(PyObject *ex) |
| 876 |
|
| 877 |
Return :attr:`~BaseException.args` of exception *ex*. |
| 878 |
|
| 879 |
|
| 880 |
.. c:function:: void PyException_SetArgs(PyObject *ex, PyObject *args) |
| 881 |
|
| 882 |
Set :attr:`~BaseException.args` of exception *ex* to *args*. |
| 883 |
|
| 884 |
.. c:function:: PyObject* PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs) |
| 885 |
|
| 886 |
Implement part of the interpreter's implementation of :keyword:`!except*`. |
| 887 |
*orig* is the original exception that was caught, and *excs* is the list of |
| 888 |
the exceptions that need to be raised. This list contains the unhandled |
| 889 |
part of *orig*, if any, as well as the exceptions that were raised from the |
| 890 |
:keyword:`!except*` clauses (so they have a different traceback from *orig*) and |
| 891 |
those that were reraised (and have the same traceback as *orig*). |
| 892 |
Return the :exc:`ExceptionGroup` that needs to be reraised in the end, or |
| 893 |
``None`` if there is nothing to reraise. |
| 894 |
|
| 895 |
.. versionadded:: 3.12 |
| 896 |
|
| 897 |
.. _unicodeexceptions: |
| 898 |
|
| 899 |
Unicode Exception Objects |
| 900 |
========================= |
| 901 |
|
| 902 |
The following functions are used to create and modify Unicode exceptions from C. |
| 903 |
|
| 904 |
.. 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) |
| 905 |
|
| 906 |
Create a :class:`UnicodeDecodeError` object with the attributes *encoding*, |
| 907 |
*object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are |
| 908 |
UTF-8 encoded strings. |
| 909 |
|
| 910 |
.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc) |
| 911 |
PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc) |
| 912 |
|
| 913 |
Return the *encoding* attribute of the given exception object. |
| 914 |
|
| 915 |
.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc) |
| 916 |
PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc) |
| 917 |
PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc) |
| 918 |
|
| 919 |
Return the *object* attribute of the given exception object. |
| 920 |
|
| 921 |
.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) |
| 922 |
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) |
| 923 |
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) |
| 924 |
|
| 925 |
Get the *start* attribute of the given exception object and place it into |
| 926 |
*\*start*. *start* must not be ``NULL``. Return ``0`` on success, ``-1`` on |
| 927 |
failure. |
| 928 |
|
| 929 |
If the :attr:`UnicodeError.object` is an empty sequence, the resulting |
| 930 |
*start* is ``0``. Otherwise, it is clipped to ``[0, len(object) - 1]``. |
| 931 |
|
| 932 |
.. seealso:: :attr:`UnicodeError.start` |
| 933 |
|
| 934 |
.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start) |
| 935 |
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start) |
| 936 |
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start) |
| 937 |
|
| 938 |
Set the *start* attribute of the given exception object to *start*. |
| 939 |
Return ``0`` on success, ``-1`` on failure. |
| 940 |
|
| 941 |
.. note:: |
| 942 |
|
| 943 |
While passing a negative *start* does not raise an exception, |
| 944 |
the corresponding getters will not consider it as a relative |
| 945 |
offset. |
| 946 |
|
| 947 |
.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end) |
| 948 |
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end) |
| 949 |
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end) |
| 950 |
|
| 951 |
Get the *end* attribute of the given exception object and place it into |
| 952 |
*\*end*. *end* must not be ``NULL``. Return ``0`` on success, ``-1`` on |
| 953 |
failure. |
| 954 |
|
| 955 |
If the :attr:`UnicodeError.object` is an empty sequence, the resulting |
| 956 |
*end* is ``0``. Otherwise, it is clipped to ``[1, len(object)]``. |
| 957 |
|
| 958 |
.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end) |
| 959 |
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end) |
| 960 |
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end) |
| 961 |
|
| 962 |
Set the *end* attribute of the given exception object to *end*. Return ``0`` |
| 963 |
on success, ``-1`` on failure. |
| 964 |
|
| 965 |
.. seealso:: :attr:`UnicodeError.end` |
| 966 |
|
| 967 |
.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc) |
| 968 |
PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc) |
| 969 |
PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc) |
| 970 |
|
| 971 |
Return the *reason* attribute of the given exception object. |
| 972 |
|
| 973 |
.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason) |
| 974 |
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason) |
| 975 |
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason) |
| 976 |
|
| 977 |
Set the *reason* attribute of the given exception object to *reason*. Return |
| 978 |
``0`` on success, ``-1`` on failure. |
| 979 |
|
| 980 |
|
| 981 |
.. _recursion: |
| 982 |
|
| 983 |
Recursion Control |
| 984 |
================= |
| 985 |
|
| 986 |
These two functions provide a way to perform safe recursive calls at the C |
| 987 |
level, both in the core and in extension modules. They are needed if the |
| 988 |
recursive code does not necessarily invoke Python code (which tracks its |
| 989 |
recursion depth automatically). |
| 990 |
They are also not needed for *tp_call* implementations |
| 991 |
because the :ref:`call protocol <call>` takes care of recursion handling. |
| 992 |
|
| 993 |
.. c:function:: int Py_EnterRecursiveCall(const char *where) |
| 994 |
|
| 995 |
Marks a point where a recursive C-level call is about to be performed. |
| 996 |
|
| 997 |
The function then checks if the stack limit is reached. If this is the |
| 998 |
case, a :exc:`RecursionError` is set and a nonzero value is returned. |
| 999 |
Otherwise, zero is returned. |
| 1000 |
|
| 1001 |
*where* should be a UTF-8 encoded string such as ``" in instance check"`` to |
| 1002 |
be concatenated to the :exc:`RecursionError` message caused by the recursion |
| 1003 |
depth limit. |
| 1004 |
|
| 1005 |
.. seealso:: |
| 1006 |
The :c:func:`PyUnstable_ThreadState_SetStackProtection` function. |
| 1007 |
|
| 1008 |
.. versionchanged:: 3.9 |
| 1009 |
This function is now also available in the :ref:`limited API <limited-c-api>`. |
| 1010 |
|
| 1011 |
.. c:function:: void Py_LeaveRecursiveCall(void) |
| 1012 |
|
| 1013 |
Ends a :c:func:`Py_EnterRecursiveCall`. Must be called once for each |
| 1014 |
*successful* invocation of :c:func:`Py_EnterRecursiveCall`. |
| 1015 |
|
| 1016 |
.. versionchanged:: 3.9 |
| 1017 |
This function is now also available in the :ref:`limited API <limited-c-api>`. |
| 1018 |
|
| 1019 |
Properly implementing :c:member:`~PyTypeObject.tp_repr` for container types requires |
| 1020 |
special recursion handling. In addition to protecting the stack, |
| 1021 |
:c:member:`~PyTypeObject.tp_repr` also needs to track objects to prevent cycles. The |
| 1022 |
following two functions facilitate this functionality. Effectively, |
| 1023 |
these are the C equivalent to :func:`reprlib.recursive_repr`. |
| 1024 |
|
| 1025 |
.. c:function:: int Py_ReprEnter(PyObject *object) |
| 1026 |
|
| 1027 |
Called at the beginning of the :c:member:`~PyTypeObject.tp_repr` implementation to |
| 1028 |
detect cycles. |
| 1029 |
|
| 1030 |
If the object has already been processed, the function returns a |
| 1031 |
positive integer. In that case the :c:member:`~PyTypeObject.tp_repr` implementation |
| 1032 |
should return a string object indicating a cycle. As examples, |
| 1033 |
:class:`dict` objects return ``{...}`` and :class:`list` objects |
| 1034 |
return ``[...]``. |
| 1035 |
|
| 1036 |
The function will return a negative integer if the recursion limit |
| 1037 |
is reached. In that case the :c:member:`~PyTypeObject.tp_repr` implementation should |
| 1038 |
typically return ``NULL``. |
| 1039 |
|
| 1040 |
Otherwise, the function returns zero and the :c:member:`~PyTypeObject.tp_repr` |
| 1041 |
implementation can continue normally. |
| 1042 |
|
| 1043 |
.. c:function:: void Py_ReprLeave(PyObject *object) |
| 1044 |
|
| 1045 |
Ends a :c:func:`Py_ReprEnter`. Must be called once for each |
| 1046 |
invocation of :c:func:`Py_ReprEnter` that returns zero. |
| 1047 |
|
| 1048 |
.. c:function:: int Py_GetRecursionLimit(void) |
| 1049 |
|
| 1050 |
Get the recursion limit for the current interpreter. It can be set with |
| 1051 |
:c:func:`Py_SetRecursionLimit`. The recursion limit prevents the |
| 1052 |
Python interpreter stack from growing infinitely. |
| 1053 |
|
| 1054 |
This function cannot fail, and the caller must hold an |
| 1055 |
:term:`attached thread state`. |
| 1056 |
|
| 1057 |
.. seealso:: |
| 1058 |
:py:func:`sys.getrecursionlimit` |
| 1059 |
|
| 1060 |
.. c:function:: void Py_SetRecursionLimit(int new_limit) |
| 1061 |
|
| 1062 |
Set the recursion limit for the current interpreter. |
| 1063 |
|
| 1064 |
This function cannot fail, and the caller must hold an |
| 1065 |
:term:`attached thread state`. |
| 1066 |
|
| 1067 |
.. seealso:: |
| 1068 |
:py:func:`sys.setrecursionlimit` |
| 1069 |
|
| 1070 |
.. _standardexceptions: |
| 1071 |
|
| 1072 |
Exception and warning types |
| 1073 |
=========================== |
| 1074 |
|
| 1075 |
All standard Python exceptions and warning categories are available as global |
| 1076 |
variables whose names are ``PyExc_`` followed by the Python exception name. |
| 1077 |
These have the type :c:expr:`PyObject*`; they are all class objects. |
| 1078 |
|
| 1079 |
For completeness, here are all the variables: |
| 1080 |
|
| 1081 |
Exception types |
| 1082 |
--------------- |
| 1083 |
|
| 1084 |
.. list-table:: |
| 1085 |
:align: left |
| 1086 |
:widths: auto |
| 1087 |
:header-rows: 1 |
| 1088 |
|
| 1089 |
* * C name |
| 1090 |
* Python name |
| 1091 |
* * .. c:var:: PyObject *PyExc_BaseException |
| 1092 |
* :exc:`BaseException` |
| 1093 |
* * .. c:var:: PyObject *PyExc_BaseExceptionGroup |
| 1094 |
* :exc:`BaseExceptionGroup` |
| 1095 |
* * .. c:var:: PyObject *PyExc_Exception |
| 1096 |
* :exc:`Exception` |
| 1097 |
* * .. c:var:: PyObject *PyExc_ArithmeticError |
| 1098 |
* :exc:`ArithmeticError` |
| 1099 |
* * .. c:var:: PyObject *PyExc_AssertionError |
| 1100 |
* :exc:`AssertionError` |
| 1101 |
* * .. c:var:: PyObject *PyExc_AttributeError |
| 1102 |
* :exc:`AttributeError` |
| 1103 |
* * .. c:var:: PyObject *PyExc_BlockingIOError |
| 1104 |
* :exc:`BlockingIOError` |
| 1105 |
* * .. c:var:: PyObject *PyExc_BrokenPipeError |
| 1106 |
* :exc:`BrokenPipeError` |
| 1107 |
* * .. c:var:: PyObject *PyExc_BufferError |
| 1108 |
* :exc:`BufferError` |
| 1109 |
* * .. c:var:: PyObject *PyExc_ChildProcessError |
| 1110 |
* :exc:`ChildProcessError` |
| 1111 |
* * .. c:var:: PyObject *PyExc_ConnectionAbortedError |
| 1112 |
* :exc:`ConnectionAbortedError` |
| 1113 |
* * .. c:var:: PyObject *PyExc_ConnectionError |
| 1114 |
* :exc:`ConnectionError` |
| 1115 |
* * .. c:var:: PyObject *PyExc_ConnectionRefusedError |
| 1116 |
* :exc:`ConnectionRefusedError` |
| 1117 |
* * .. c:var:: PyObject *PyExc_ConnectionResetError |
| 1118 |
* :exc:`ConnectionResetError` |
| 1119 |
* * .. c:var:: PyObject *PyExc_EOFError |
| 1120 |
* :exc:`EOFError` |
| 1121 |
* * .. c:var:: PyObject *PyExc_FileExistsError |
| 1122 |
* :exc:`FileExistsError` |
| 1123 |
* * .. c:var:: PyObject *PyExc_FileNotFoundError |
| 1124 |
* :exc:`FileNotFoundError` |
| 1125 |
* * .. c:var:: PyObject *PyExc_FloatingPointError |
| 1126 |
* :exc:`FloatingPointError` |
| 1127 |
* * .. c:var:: PyObject *PyExc_GeneratorExit |
| 1128 |
* :exc:`GeneratorExit` |
| 1129 |
* * .. c:var:: PyObject *PyExc_ImportError |
| 1130 |
* :exc:`ImportError` |
| 1131 |
* * .. c:var:: PyObject *PyExc_IndentationError |
| 1132 |
* :exc:`IndentationError` |
| 1133 |
* * .. c:var:: PyObject *PyExc_IndexError |
| 1134 |
* :exc:`IndexError` |
| 1135 |
* * .. c:var:: PyObject *PyExc_InterruptedError |
| 1136 |
* :exc:`InterruptedError` |
| 1137 |
* * .. c:var:: PyObject *PyExc_IsADirectoryError |
| 1138 |
* :exc:`IsADirectoryError` |
| 1139 |
* * .. c:var:: PyObject *PyExc_KeyError |
| 1140 |
* :exc:`KeyError` |
| 1141 |
* * .. c:var:: PyObject *PyExc_KeyboardInterrupt |
| 1142 |
* :exc:`KeyboardInterrupt` |
| 1143 |
* * .. c:var:: PyObject *PyExc_LookupError |
| 1144 |
* :exc:`LookupError` |
| 1145 |
* * .. c:var:: PyObject *PyExc_MemoryError |
| 1146 |
* :exc:`MemoryError` |
| 1147 |
* * .. c:var:: PyObject *PyExc_ModuleNotFoundError |
| 1148 |
* :exc:`ModuleNotFoundError` |
| 1149 |
* * .. c:var:: PyObject *PyExc_NameError |
| 1150 |
* :exc:`NameError` |
| 1151 |
* * .. c:var:: PyObject *PyExc_NotADirectoryError |
| 1152 |
* :exc:`NotADirectoryError` |
| 1153 |
* * .. c:var:: PyObject *PyExc_NotImplementedError |
| 1154 |
* :exc:`NotImplementedError` |
| 1155 |
* * .. c:var:: PyObject *PyExc_OSError |
| 1156 |
* :exc:`OSError` |
| 1157 |
* * .. c:var:: PyObject *PyExc_OverflowError |
| 1158 |
* :exc:`OverflowError` |
| 1159 |
* * .. c:var:: PyObject *PyExc_PermissionError |
| 1160 |
* :exc:`PermissionError` |
| 1161 |
* * .. c:var:: PyObject *PyExc_ProcessLookupError |
| 1162 |
* :exc:`ProcessLookupError` |
| 1163 |
* * .. c:var:: PyObject *PyExc_PythonFinalizationError |
| 1164 |
* :exc:`PythonFinalizationError` |
| 1165 |
* * .. c:var:: PyObject *PyExc_RecursionError |
| 1166 |
* :exc:`RecursionError` |
| 1167 |
* * .. c:var:: PyObject *PyExc_ReferenceError |
| 1168 |
* :exc:`ReferenceError` |
| 1169 |
* * .. c:var:: PyObject *PyExc_RuntimeError |
| 1170 |
* :exc:`RuntimeError` |
| 1171 |
* * .. c:var:: PyObject *PyExc_StopAsyncIteration |
| 1172 |
* :exc:`StopAsyncIteration` |
| 1173 |
* * .. c:var:: PyObject *PyExc_StopIteration |
| 1174 |
* :exc:`StopIteration` |
| 1175 |
* * .. c:var:: PyObject *PyExc_SyntaxError |
| 1176 |
* :exc:`SyntaxError` |
| 1177 |
* * .. c:var:: PyObject *PyExc_SystemError |
| 1178 |
* :exc:`SystemError` |
| 1179 |
* * .. c:var:: PyObject *PyExc_SystemExit |
| 1180 |
* :exc:`SystemExit` |
| 1181 |
* * .. c:var:: PyObject *PyExc_TabError |
| 1182 |
* :exc:`TabError` |
| 1183 |
* * .. c:var:: PyObject *PyExc_TimeoutError |
| 1184 |
* :exc:`TimeoutError` |
| 1185 |
* * .. c:var:: PyObject *PyExc_TypeError |
| 1186 |
* :exc:`TypeError` |
| 1187 |
* * .. c:var:: PyObject *PyExc_UnboundLocalError |
| 1188 |
* :exc:`UnboundLocalError` |
| 1189 |
* * .. c:var:: PyObject *PyExc_UnicodeDecodeError |
| 1190 |
* :exc:`UnicodeDecodeError` |
| 1191 |
* * .. c:var:: PyObject *PyExc_UnicodeEncodeError |
| 1192 |
* :exc:`UnicodeEncodeError` |
| 1193 |
* * .. c:var:: PyObject *PyExc_UnicodeError |
| 1194 |
* :exc:`UnicodeError` |
| 1195 |
* * .. c:var:: PyObject *PyExc_UnicodeTranslateError |
| 1196 |
* :exc:`UnicodeTranslateError` |
| 1197 |
* * .. c:var:: PyObject *PyExc_ValueError |
| 1198 |
* :exc:`ValueError` |
| 1199 |
* * .. c:var:: PyObject *PyExc_ZeroDivisionError |
| 1200 |
* :exc:`ZeroDivisionError` |
| 1201 |
|
| 1202 |
.. versionadded:: 3.3 |
| 1203 |
:c:data:`PyExc_BlockingIOError`, :c:data:`PyExc_BrokenPipeError`, |
| 1204 |
:c:data:`PyExc_ChildProcessError`, :c:data:`PyExc_ConnectionError`, |
| 1205 |
:c:data:`PyExc_ConnectionAbortedError`, :c:data:`PyExc_ConnectionRefusedError`, |
| 1206 |
:c:data:`PyExc_ConnectionResetError`, :c:data:`PyExc_FileExistsError`, |
| 1207 |
:c:data:`PyExc_FileNotFoundError`, :c:data:`PyExc_InterruptedError`, |
| 1208 |
:c:data:`PyExc_IsADirectoryError`, :c:data:`PyExc_NotADirectoryError`, |
| 1209 |
:c:data:`PyExc_PermissionError`, :c:data:`PyExc_ProcessLookupError` |
| 1210 |
and :c:data:`PyExc_TimeoutError` were introduced following :pep:`3151`. |
| 1211 |
|
| 1212 |
.. versionadded:: 3.5 |
| 1213 |
:c:data:`PyExc_StopAsyncIteration` and :c:data:`PyExc_RecursionError`. |
| 1214 |
|
| 1215 |
.. versionadded:: 3.6 |
| 1216 |
:c:data:`PyExc_ModuleNotFoundError`. |
| 1217 |
|
| 1218 |
.. versionadded:: 3.11 |
| 1219 |
:c:data:`PyExc_BaseExceptionGroup`. |
| 1220 |
|
| 1221 |
|
| 1222 |
OSError aliases |
| 1223 |
--------------- |
| 1224 |
|
| 1225 |
The following are a compatibility aliases to :c:data:`PyExc_OSError`. |
| 1226 |
|
| 1227 |
.. versionchanged:: 3.3 |
| 1228 |
These aliases used to be separate exception types. |
| 1229 |
|
| 1230 |
.. list-table:: |
| 1231 |
:align: left |
| 1232 |
:widths: auto |
| 1233 |
:header-rows: 1 |
| 1234 |
|
| 1235 |
* * C name |
| 1236 |
* Python name |
| 1237 |
* Notes |
| 1238 |
* * .. c:var:: PyObject *PyExc_EnvironmentError |
| 1239 |
* :exc:`OSError` |
| 1240 |
* |
| 1241 |
* * .. c:var:: PyObject *PyExc_IOError |
| 1242 |
* :exc:`OSError` |
| 1243 |
* |
| 1244 |
* * .. c:var:: PyObject *PyExc_WindowsError |
| 1245 |
* :exc:`OSError` |
| 1246 |
* [win]_ |
| 1247 |
|
| 1248 |
Notes: |
| 1249 |
|
| 1250 |
.. [win] |
| 1251 |
:c:var:`!PyExc_WindowsError` is only defined on Windows; protect code that |
| 1252 |
uses this by testing that the preprocessor macro ``MS_WINDOWS`` is defined. |
| 1253 |
|
| 1254 |
|
| 1255 |
.. _standardwarningcategories: |
| 1256 |
|
| 1257 |
Warning types |
| 1258 |
------------- |
| 1259 |
|
| 1260 |
.. list-table:: |
| 1261 |
:align: left |
| 1262 |
:widths: auto |
| 1263 |
:header-rows: 1 |
| 1264 |
|
| 1265 |
* * C name |
| 1266 |
* Python name |
| 1267 |
* * .. c:var:: PyObject *PyExc_Warning |
| 1268 |
* :exc:`Warning` |
| 1269 |
* * .. c:var:: PyObject *PyExc_BytesWarning |
| 1270 |
* :exc:`BytesWarning` |
| 1271 |
* * .. c:var:: PyObject *PyExc_DeprecationWarning |
| 1272 |
* :exc:`DeprecationWarning` |
| 1273 |
* * .. c:var:: PyObject *PyExc_EncodingWarning |
| 1274 |
* :exc:`EncodingWarning` |
| 1275 |
* * .. c:var:: PyObject *PyExc_FutureWarning |
| 1276 |
* :exc:`FutureWarning` |
| 1277 |
* * .. c:var:: PyObject *PyExc_ImportWarning |
| 1278 |
* :exc:`ImportWarning` |
| 1279 |
* * .. c:var:: PyObject *PyExc_PendingDeprecationWarning |
| 1280 |
* :exc:`PendingDeprecationWarning` |
| 1281 |
* * .. c:var:: PyObject *PyExc_ResourceWarning |
| 1282 |
* :exc:`ResourceWarning` |
| 1283 |
* * .. c:var:: PyObject *PyExc_RuntimeWarning |
| 1284 |
* :exc:`RuntimeWarning` |
| 1285 |
* * .. c:var:: PyObject *PyExc_SyntaxWarning |
| 1286 |
* :exc:`SyntaxWarning` |
| 1287 |
* * .. c:var:: PyObject *PyExc_UnicodeWarning |
| 1288 |
* :exc:`UnicodeWarning` |
| 1289 |
* * .. c:var:: PyObject *PyExc_UserWarning |
| 1290 |
* :exc:`UserWarning` |
| 1291 |
|
| 1292 |
.. versionadded:: 3.2 |
| 1293 |
:c:data:`PyExc_ResourceWarning`. |
| 1294 |
|
| 1295 |
.. versionadded:: 3.10 |
| 1296 |
:c:data:`PyExc_EncodingWarning`. |
| 1297 |
|
| 1298 |
|
| 1299 |
Tracebacks |
| 1300 |
========== |
| 1301 |
|
| 1302 |
.. c:var:: PyTypeObject PyTraceBack_Type |
| 1303 |
|
| 1304 |
Type object for traceback objects. This is available as |
| 1305 |
:class:`types.TracebackType` in the Python layer. |
| 1306 |
|
| 1307 |
|
| 1308 |
.. c:function:: int PyTraceBack_Check(PyObject *op) |
| 1309 |
|
| 1310 |
Return true if *op* is a traceback object, false otherwise. This function |
| 1311 |
does not account for subtypes. |
| 1312 |
|
| 1313 |
|
| 1314 |
.. c:function:: int PyTraceBack_Here(PyFrameObject *f) |
| 1315 |
|
| 1316 |
Replace the :attr:`~BaseException.__traceback__` attribute on the current |
| 1317 |
exception with a new traceback prepending *f* to the existing chain. |
| 1318 |
|
| 1319 |
Calling this function without an exception set is undefined behavior. |
| 1320 |
|
| 1321 |
This function returns ``0`` on success, and returns ``-1`` with an |
| 1322 |
exception set on failure. |
| 1323 |
|
| 1324 |
|
| 1325 |
.. c:function:: int PyTraceBack_Print(PyObject *tb, PyObject *f) |
| 1326 |
|
| 1327 |
Write the traceback *tb* into the file *f*. |
| 1328 |
|
| 1329 |
This function returns ``0`` on success, and returns ``-1`` with an |
| 1330 |
exception set on failure. |