Can we in python code, catch exception generated by C++ pythonized function?

Mark Hammond mhammond at my-deja.com
Fri Jan 12 20:44:29 EST 2001


In article <3A5FAA6E.ABA298AB at aristotech.com>,
  Siu-Tong Hui <tong at aristotech.com> wrote:
> Thanks for all the responses.
>
> We use SWIG to link from python to C++. Our highest level code is in
> python.
...

> level command shell, we would have to put in exception control
> codes in all pythonized C++ functions in order to have
> bullet-proof exception protection. If I can catch exception in
> python, then I only need to do it once in my highest level command
> shell in python.

You can't catch C++ exceptions directly in Python.  But check out the
SWIG %except typedef.  You should be able to say something like:

%typemap(python,except) MYBOOL {
      try {
         $function
      } catch (e) {
         PyErr_SetString(MyError, e->description_or_whatever);
         return NULL;
      }
}

This is the technique I use to ensure that most SWIG wrapped functions
in the Win32 extensions correctly convert Win32 error codes to Python
exceptions - see pywintypes.i in the Python for win32 sources.

Mark.


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list