How to exit Python nicely after error in embedded C code?

Alex Martelli aleaxit at yahoo.com
Tue Feb 27 11:17:46 EST 2001


"Louis Luangkesorn" <lluang at northwestern.edu> wrote in message
news:3A9BBD28.8F537F75 at northwestern.edu...
    [talking about "exceptions" from C vs C++]
> (I'm asking this out of complete ignorance, obviously)
> In this situation (error occurs in a C function that is called by other C
> functions which are called by Python), would having the original C call
from
> Python in a try...except block catch the exception?  (I'm just learning
how to
> do this, in both C++ and Python, but I have not done this in real life
yet.  It
> seems like a nice, cheap way of using exceptions in C, just call
everything from
> Python :-)

The C language does not define nor use exceptions.

The Python C API, therefore, does not use them either.  Python is
entirely coded in C, to the C89 standard of ANSI and later ISO, not
in C++.

_Python_ exceptions are not the same thing as _C++_ exceptions.
A "Python Exception" is "raised" by a C-coded function, in an
extension, that is called by Python, by returning 0 (aka NULL)
as its PyObject* (and some previous Python C API calls to give
the exceptions' details).

There are several frameworks that make it easier to extend Python
by harnessing (some of) the extra power of C++ wrt C: CXX, SCXX,
the Boost Python Library (BPL, part of the free Boost collection,
see www.boost.org), and others yet.  Some of them do make use of
the power of C++ exceptions, somewhat in the way you suggest, and,
also, may bridge/translate between C++ exceptions and Python ones.

But there is no clean, portable way to "raise an exception" if you
choose to use C, rather than C++, to code your Python extensions,
and you find yourself in a C function called by a C function [repeat
down a few nesting levels...] called by Python.  Either switch to
C++ (and some appropriate C++/Python framework such as the BPL), or
live with patiently returning an error indication from the deeply
nested function, and checking-and-propagating-upwards in each
caller.

That is, of course, IF you care about portability; if you don't, you
may experiment to see what your platform[s] of interest will allow
in a setjmp/longjmp pair, which is the closest thing that C offers
to "exceptions" (just take a *LOT* of care about memory leaks &c,
as you get absolutely no protection, no equivalent of C++'s automatic
execution of destructors as the stack is unwound due to exceptions).


Alex






More information about the Python-list mailing list