Exception Handling

The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand some of the basics of Python exception handling. It works somewhat like the POSIX errno variable: there is a global indicator (per thread) of the last error that occurred. Most C API functions don’t clear this on success, but will set it to indicate the cause of the error on failure. Most C API functions also return an error indicator, usually NULL if they are supposed to return a pointer, or -1 if they return an integer (exception: the PyArg_* functions return 1 for success and 0 for failure).

Concretely, the error indicator consists of three object pointers: the exception’s type, the exception’s value, and the traceback object. Any of those pointers can be NULL if non-set (although some combinations are forbidden, for example you can’t have a non-NULL traceback if the exception type is NULL).

When a function must fail because some function it called failed, it generally doesn’t set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should not continue normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways.

Note

The error indicator is not the result of sys.exc_info(). The former corresponds to an exception that is not yet caught (and is therefore still propagating), while the latter returns an exception after it is caught (and has therefore stopped propagating).

Printing and clearing

void PyErr_Clear()
Part of the Stable ABI.

Clear the error indicator. If the error indicator is not set, there is no effect.

void PyErr_PrintEx(int set_sys_last_vars)
Part of the Stable ABI.

Print a standard traceback to sys.stderr and clear the error indicator. Unless the error is a SystemExit, in that case no traceback is printed and the Python process will exit with the error code specified by the SystemExit instance.

Call this function only when the error indicator is set. Otherwise it will cause a fatal error!

If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For backwards compatibility, the deprecated variables sys.last_type, sys.last_value and sys.last_traceback are also set to the type, value and traceback of this exception, respectively.

Changed in version 3.12: The setting of sys.last_exc was added.

void PyErr_Print()
Part of the Stable ABI.

Alias for PyErr_PrintEx(1).

void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI.

Call sys.unraisablehook() using the current exception and obj argument.

This utility function prints a warning message to sys.stderr when an exception has been set but it is impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an __del__() method.

The function is called with a single argument obj that identifies the context in which the unraisable exception occurred. If possible, the repr of obj will be printed in the warning message. If obj is NULL, only the traceback is printed.

An exception must be set when calling this function.

Changed in version 3.4: Print a traceback. Print only traceback if obj is NULL.

Changed in version 3.8: Use sys.unraisablehook().

void PyErr_FormatUnraisable(const char *format, ...)

Similar to PyErr_WriteUnraisable(), but the format and subsequent parameters help format the warning message; they have the same meaning and values as in PyUnicode_FromFormat(). PyErr_WriteUnraisable(obj) is roughly equivalent to PyErr_FormatUnraisable("Exception ignored in: %R", obj). If format is NULL, only the traceback is printed.

Added in version 3.13.

void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12.

Print the standard traceback display of exc to sys.stderr, including chained exceptions and notes.

Added in version 3.12.

Raising exceptions

These functions help you set the current thread’s error indicator. For convenience, some of these functions will always return a NULL pointer for use in a return statement.

void PyErr_SetString(PyObject *type, const char *message)
Part of the Stable ABI.

This is the most common way to set the error indicator. The first argument specifies the exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not create a new strong reference to it (e.g. with Py_INCREF()). The second argument is an error message; it is decoded from 'utf-8'.

void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI.

This function is similar to PyErr_SetString() but lets you specify an arbitrary Python object for the “value” of the exception.

PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Return value: Always NULL. Part of the Stable ABI.

This function sets the error indicator and returns NULL. exception should be a Python exception class. The format and subsequent parameters help format the error message; they have the same meaning and values as in PyUnicode_FromFormat(). format is an ASCII-encoded string.

PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5.

Same as PyErr_Format(), but taking a va_list argument rather than a variable number of arguments.

Added in version 3.5.

void PyErr_SetNone(PyObject *type)
Part of the Stable ABI.

This is a shorthand for PyErr_SetObject(type, Py_None).

int PyErr_BadArgument()
Part of the Stable ABI.

This is a shorthand for PyErr_SetString(PyExc_TypeError, message), where message indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use.

PyObject *PyErr_NoMemory()
Return value: Always NULL. Part of the Stable ABI.

This is a shorthand for PyErr_SetNone(PyExc_MemoryError); it returns NULL so an object allocation function can write return PyErr_NoMemory(); when it runs out of memory.

PyObject *PyErr_SetFromErrno(PyObject *type)
Return value: Always NULL. Part of the Stable ABI.

This is a convenience function to raise an exception when a C library function has returned an error and set the C variable errno. It constructs a tuple object whose first item is the integer errno value and whose second item is the corresponding error message (gotten from strerror()), and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns NULL, so a wrapper function around a system call can write return PyErr_SetFromErrno(type); when the system call returns an error.

PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Return value: Always NULL. Part of the Stable ABI.

Similar to PyErr_SetFromErrno(), with the additional behavior that if filenameObject is not NULL, it is passed to the constructor of type as a third parameter. In the case of OSError exception, this is used to define the filename attribute of the exception instance.

PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)
Return value: Always NULL. Part of the Stable ABI since version 3.7.

Similar to PyErr_SetFromErrnoWithFilenameObject(), but takes a second filename object, for raising errors when a function that takes two filenames fails.

Added in version 3.4.

PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
Return value: Always NULL. Part of the Stable ABI.

Similar to PyErr_SetFromErrnoWithFilenameObject(), but the filename is given as a C string. filename is decoded from the filesystem encoding and error handler.