The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand some of the basics of Python exception handling. It works somewhat like the Unix :c:data:`errno` variable: there is a global indicator (per thread) of the last error that occurred. Most functions don't clear this on success, but will set it to indicate the cause of the error on failure. Most functions also return an error indicator, usually NULL if they are supposed to return a pointer, or -1 if they return an integer (exception: the :c:func:`PyArg_\*` functions return 1 for success and 0 for failure).
When a function must fail because some function it called failed, it generally doesn't set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should not continue normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways.
The error indicator consists of three Python objects corresponding to the Python variables sys.exc_type, sys.exc_value and sys.exc_traceback. API functions exist to interact with the error indicator in various ways. There is a separate error indicator for each thread.
Unicode Exception Objects
The following functions are used to create and modify Unicode exceptions from C.
These two functions provide a way to perform safe recursive calls at the C level, both in the core and in extension modules. They are needed if the recursive code does not necessarily invoke Python code (which tracks its recursion depth automatically).
All standard Python exceptions are available as global variables whose names are PyExc_ followed by the Python exception name. These have the type :c:type:`PyObject\*`; they are all class objects. For completeness, here are all the variables:
- This is a base class for other standard exceptions.
- This is the same as :exc:`weakref.ReferenceError`.
- Only defined on Windows; protect code that uses this by testing that the preprocessor macro MS_WINDOWS is defined.