C API's Essential Check for Pending Errors
The `PyErr_Occurred()` function is the indispensable C API call for determining if a Python exception has been set and requires propagation or specific handling within C code.
The top 3
- Top 3 Silent Failures from Missing C API Error Checks: Neglecting to check for pending Python exceptions in C API extensions can lead to severe, silent failures, including memory leaks, corrupted interpreter state, and unexpected program crashes (SIGABRT) that are notoriously difficult to debug. [1, 2, 9]
- Essential C API Error State Functions: PyErr_Occurred vs. PyErr_Fetch: The core function `PyErr_Occurred()` checks if an exception is pending, returning a borrowed reference to the exception type or `NULL`. For retrieving and temporarily clearing the full exception state (type, value, traceback) for advanced handling, `PyErr_Fetch()` is used. [1, 3, 4, 8, 10]
- Top 3 C API Patterns for Propagating Python Exceptions: When a C API function encounters an error, the standard practice is to set the exception indicator and return an error sentinel (e.g., `NULL` for `PyObject*` or `-1` for integers). The calling C function should then clean up its resources (often using `goto error` and `Py_XDECREF`) and propagate the existing error by returning its own error indicator, rather than setting a new exception and overwriting crucial error details. [1, 2, 3, 7, 9, 10]
Sources
Open the full topic