Catching exceptions from C/C++ extensions

Andrew Gregory andrew.gregory at npl.co.uk
Mon Jan 13 07:37:06 EST 2003


I've written an extension which defines it's own exception class:

// In initialisation section
   static PyObject* Myerror;

   Myerror = PyErr_NewException("_mymodule.Myerror", NULL, NULL);
   if (Myerror != NULL)
   PyDict_SetItemString(d, "My error", Myerror);


// Then from a function in the event of an error I can create a python
// exception using: 
    PyErr_SetString(Myerror, message_string);
    return NULL;

Now, this all works fine up to a point. In the event of an error I get
something like:

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "C:\pyfiles\mymodule.py", line 61, in myfunc
    def myfunc(*args): return apply(_mymodule.myClass_myfunc,args)
Myerror: Error in my function

Which is just what I would expect. But if in a script file I have
something like

import mymodule

  try:
      y=myfunc()
  except Myerror:

I get

  NameError: name 'Myerror' is not defined 

in the event of an exception.

How do I go about catching these exceptions? It seems that Myerror
does not have global scope.



*** More info ***

I used SWIG to generate a wrapper file. The interface file looks like:

%header
%{
   static PyObject* Myerror;
%};


%module mymodule
%{
   #include "mymodule.h"
%}


// Extend initialisation section in wrapper to provide new Exception
class
%init
%{
   Myerror = PyErr_NewException("_mymodule.Myerror", NULL, NULL);
   if (Myerror != NULL)
   PyDict_SetItemString(d, "My error", Myerror);

%};

%include mymodule.h

As far as I can see "static PyObject *Myerror;" really is in the outer
block of the wrapper.

Andrew.




More information about the Python-list mailing list