Exception Handling¶
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 :cdata:`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 :cfunc:`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.
Recursion Control¶
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).
Standard Exceptions¶
All standard Python exceptions are available as global variables whose names are
PyExc_
followed by the Python exception name. These have the type
:ctype:`PyObject\*`; they are all class objects. For completeness, here are all
the variables:
Notes:
This is a base class for other standard exceptions.
This is the same as
weakref.ReferenceError
.Only defined on Windows; protect code that uses this by testing that the preprocessor macro
MS_WINDOWS
is defined.New in version 2.5.
Deprecation of String Exceptions¶
All exceptions built into Python or provided in the standard library are derived
from BaseException
.
String exceptions are still supported in the interpreter to allow existing code to run unmodified, but this will also change in a future release.