Overview
Exception handling in C extensions requires explicit checking of return values and managing the exception state.Checking for Exceptions
NULL if no exception
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Raising and handling Python exceptions in C
PyObject* PyErr_Occurred(void)
NULL if no exception
void PyErr_SetString(PyObject *type, const char *message)
if (value < 0) {
PyErr_SetString(PyExc_ValueError, "Value must be non-negative");
return NULL;
}
PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
if (index >= size) {
PyErr_Format(PyExc_IndexError,
"Index %d out of range (size=%d)",
index, size);
return NULL;
}
PyExc_Exception
PyExc_TypeError
PyExc_ValueError
PyExc_IndexError
PyExc_KeyError
PyExc_MemoryError
PyExc_RuntimeError
PyExc_IOError
PyExc_AttributeError
void PyErr_Clear(void)
PyObject *item = PyDict_GetItem(dict, key);
if (item == NULL && PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear();
// Handle missing key
item = default_value;
} else {
return NULL; // Propagate other errors
}
}
int PyErr_ExceptionMatches(PyObject *exc)
void PyErr_Print(void)
void PyErr_PrintEx(int set_sys_last_vars)
PyObject* PyErr_NewException(const char *name,
PyObject *base,
PyObject *dict)
static PyObject *SpamError;
PyMODINIT_FUNC PyInit_spam(void) {
PyObject *m = PyModule_Create(&spammodule);
if (m == NULL)
return NULL;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_XINCREF(SpamError);
if (PyModule_AddObject(m, "error", SpamError) < 0) {
Py_XDECREF(SpamError);
Py_CLEAR(SpamError);
Py_DECREF(m);
return NULL;
}
return m;
}
static PyObject* risky_function(PyObject *self, PyObject *args) {
PyObject *a = NULL, *b = NULL, *result = NULL;
a = PyList_New(0);
if (a == NULL)
goto error;
b = PyDict_New();
if (b == NULL)
goto error;
// Perform operations...
result = process(a, b);
if (result == NULL)
goto error;
Py_DECREF(a);
Py_DECREF(b);
return result;
error:
Py_XDECREF(a);
Py_XDECREF(b);
return NULL;
}
