Custom Python Exception in C Extension: Step-by-Step
In this article
Creating a custom exception type in a Python C extension lets you raise domain-specific errors that integrate cleanly with Python's exception hierarchy. This is useful when your extension needs to signal errors that are distinct from built-in exceptions, allowing Python code to catch them specifically. You'll need a working knowledge of the Python C API, a C compiler, and Python development headers (usually installed via python3-dev or similar).
What You'll Need
- Python development headers (e.g.,
python3-devon Debian/Ubuntu, or Xcode command line tools on macOS) - A C compiler (gcc, clang, or MSVC)
- Python's build system: either
setuptoolswith asetup.pyor a simple Makefile - Basic familiarity with the Python C API (PyObject, PyTypeObject, module initialization)
Step-by-Step
- Define the exception object – In your C source file, declare a static
PyObject *variable to hold the exception. For example:static PyObject *MyCustomError; - Create the exception in module initialization – In your module's initialization function (e.g.,
PyInit_mymodule), callPyErr_NewExceptionto create the exception. The signature is:PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict). Pass the fully qualified name like"mymodule.MyCustomError", the base exception (typicallyPyExc_Exceptionor a more specific built-in), andNULLfor dict. - Add the exception to the module – After creating the exception, add it to the module's dictionary using
PyModule_AddObject(orPyModule_AddObjectRefin Python 3.10+). For example:PyModule_AddObject(m, "MyCustomError", MyCustomError);– note that this steals a reference, so you don't need to decref it separately. - Raise the exception in your C functions – When an error condition occurs, call
PyErr_SetString(MyCustomError, "descriptive message")orPyErr_SetObject(MyCustomError, args)and returnNULLfrom the function. - Handle reference counting correctly – If you use
PyModule_AddObject, it steals a reference. If you need to keep a reference for later use (e.g., to raise the exception), you should incref it before adding, or usePyModule_AddObjectRefwhich doesn't steal. The typical pattern is:MyCustomError = PyErr_NewException(...); Py_INCREF(MyCustomError); PyModule_AddObject(m, "MyCustomError", MyCustomError);– but this is redundant becausePyErr_NewExceptionreturns a new reference andPyModule_AddObjectsteals it. If you need to keep the global variable, you must incref before adding. - Test the exception – Write a small Python test script that imports your module and catches the exception:
try: mymodule.raise_error() except mymodule.MyCustomError as e: print(e) - Build and install – Use a
setup.pywith setuptools, or compile manually. For setuptools, define an Extension object and callsetup(). Then runpython setup.py build_ext --inplaceto test locally.
Common Mistakes
- Forgetting to add the exception to the module – Without this, the exception exists but is not accessible from Python code.
- Using the wrong base exception – If you use
PyExc_BaseExceptionas base, the exception won't be catchable byexcept Exception, which may surprise users. - Incorrect reference counting – Over-decrementing or under-decrementing the exception object can cause crashes or memory leaks. Always follow the API's ownership rules.
- Not returning NULL after raising – If you raise an exception but return a non-NULL value, Python won't see the error and may continue with invalid state.
- Using a static string for the exception name – The name must be a fully qualified dotted string; otherwise, the exception's
__module__will be wrong.
Tips
- Use
PyErr_NewExceptionWithDoc(Python 3.10+) to add a docstring to your exception. - For more complex exceptions with custom attributes, you can create a full
PyTypeObjectand add it to the module manually, butPyErr_NewExceptionis sufficient for most cases. - Consider inheriting from a specific built-in like
ValueErrororRuntimeErrorto make your exception more semantically meaningful. - Always check the return value of
PyModule_AddObject– it returns -1 on failure, and you should handle that. - In Python 3, use
PyModule_AddObjectRefif you want to avoid the reference-stealing behavior and keep a reference for later.
Troubleshooting
- ImportError: cannot import name 'MyCustomError' – Check that you called
PyModule_AddObjectwith the correct name string and that the module initialization succeeded. Also ensure you're not using a stale build – rebuild with--force. - Segfault when raising the exception – Likely a reference counting issue. Ensure that
MyCustomErroris still alive when you callPyErr_SetString. If you usedPyModule_AddObject, it steals the reference, but if you also stored it in a global without incref, the global becomes a dangling pointer after the module is finalized. - Exception not catchable – Verify that the base exception is correct. If you used
PyExc_BaseException, it won't be caught byexcept Exception. Also check that the module name in the exception name matches the actual module name. - Memory leak – If you incref the exception but never decref it, you'll leak. Use
PyModule_AddObjectRef(Python 3.10+) to avoid this, or manually decref when you're done. - Build errors – Make sure Python.h is in your include path. On some systems, you need to use
python3-config --includesto get the right flags.
Frequently Asked Questions
Can I create a custom exception without a full type object?
Yes, PyErr_NewException does exactly that – it creates a simple exception type with just a name and base. For most needs, this is sufficient.
How do I add custom attributes to my exception?
You can either subclass the exception in Python and add attributes there, or create a full PyTypeObject with a custom tp_new and tp_init that sets attributes. The latter is more complex but gives full control.
Do I need to call Py_INCREF on the exception after creating it?
Only if you want to keep a reference beyond the module initialization. If you use PyModule_AddObject, it steals the reference, so you don't need to incref unless you also store it in a global variable that you use later (e.g., to raise it). In that case, incref before adding.
Can I raise the exception from a C function that returns a non-NULL value?
You can, but it's not recommended. Python checks the error indicator only if the function returns NULL. If you return a non-NULL value, the exception is ignored, which can lead to subtle bugs. Always return NULL after setting an exception.
How do I make the exception pickleable?
Exceptions created with PyErr_NewException are automatically pickleable if the module is importable. You don't need to do anything special.
What's the difference between PyModule_AddObject and PyModule_AddObjectRef?
The former steals a reference to the object, so you should not decref it afterwards. The latter increments the reference count, so you still own the original reference and must decref it when done. Use PyModule_AddObjectRef if you want to keep using the object after adding it to the module.