User Agents

Web browsers and everyday web tech, explained

Custom Python Exception in C Extension: Step-by-Step

· 5 min read · Extensions

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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-dev on Debian/Ubuntu, or Xcode command line tools on macOS)
  • A C compiler (gcc, clang, or MSVC)
  • Python's build system: either setuptools with a setup.py or a simple Makefile
  • Basic familiarity with the Python C API (PyObject, PyTypeObject, module initialization)

Step-by-Step

  1. Define the exception object – In your C source file, declare a static PyObject * variable to hold the exception. For example: static PyObject *MyCustomError;
  2. Create the exception in module initialization – In your module's initialization function (e.g., PyInit_mymodule), call PyErr_NewException to 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 (typically PyExc_Exception or a more specific built-in), and NULL for dict.
  3. Add the exception to the module – After creating the exception, add it to the module's dictionary using PyModule_AddObject (or PyModule_AddObjectRef in 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.
  4. Raise the exception in your C functions – When an error condition occurs, call PyErr_SetString(MyCustomError, "descriptive message") or PyErr_SetObject(MyCustomError, args) and return NULL from the function.
  5. 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 use PyModule_AddObjectRef which doesn't steal. The typical pattern is: MyCustomError = PyErr_NewException(...); Py_INCREF(MyCustomError); PyModule_AddObject(m, "MyCustomError", MyCustomError); – but this is redundant because PyErr_NewException returns a new reference and PyModule_AddObject steals it. If you need to keep the global variable, you must incref before adding.
  6. 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)
  7. Build and install – Use a setup.py with setuptools, or compile manually. For setuptools, define an Extension object and call setup(). Then run python setup.py build_ext --inplace to 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_BaseException as base, the exception won't be catchable by except 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 PyTypeObject and add it to the module manually, but PyErr_NewException is sufficient for most cases.
  • Consider inheriting from a specific built-in like ValueError or RuntimeError to 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_AddObjectRef if 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_AddObject with 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 MyCustomError is still alive when you call PyErr_SetString. If you used PyModule_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 by except 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 --includes to 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.