The stated goal of this chapter is to enable the reader to write an extension providing a (procdedural) Pythonic interface to some C library. We're nearly there, but after perhaps reading the reference documentation on format strings and some of the concrete types, the big gap is the handling of errors.
We've touched on the matter of coping with exceptions: that if you detect that a function you've called has raised an exception, you should pass this on to your caller without delay. But what if the error situation is in a C library you've called? You could pass an error code back to your Python caller, but that's hardly Pythonic. We need to be able to set an exception of our own.
Also, occasionally one needs to handle exceptions raised by functions you call, i.e. to write the C equivalent of:
try: func() except KeyError: pass
(the C equivalent of a bare
except: statement is just as bad an
idea in C as it is in Python. Or possibly even worse.)
Probably the most commonly used exception setting function is
PyAPI_FUNC(void) PyErr_SetString(PyObject *exception, const char *string);
exception should be an exception class. The standard Python
exception classes are all available to C code as global variables
PyExc_ and the Python name of the exception, so
ArithmeticError in Python is
in C. string is the error message that will be converted to a
THIS DOCUMENT IS A DRAFT! Comments to firstname.lastname@example.org please.