Catching exceptions from C/C++ extensions

Andrew Gregory andrew.gregory at npl.co.uk
Tue Jan 14 05:37:05 EST 2003


Looking at the wrapper file, I wonder if the new exception type should go into
the "main" dictionary. Does anyone know how to achieve this?

*** Extract from wrapper ***

    m = Py_InitModule((char *) SWIG_name, SwigMethods);
    d = PyModule_GetDict(m);

    [snip]

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


*** Test program ****

import mymodule

h=mymodule.Myclass()

try:
    print h.MyFunc(0)
except MyError: print "Caught"

# except h.MyError: print "Caught"
# except mymodule.MyError: print "Caught"

(none of above except statements works)


*** C++ code ***
// * Error object must be Myerror defined in SWIG interface file *
typedef PyObject* RESULTOBJ;
#define pyfail NULL


// Set Python error string
void SetError(char *es)
{
   PyErr_SetString(MyError, es);	  
}; 
 
class Myclass
{  
  // Hand-coded wrapper for returning int
  RESULTOBJ wrap_int(int i)
  {
    RESULTOBJ result;
    result = PyInt_FromLong(i);
    return Py_BuildValue("O",result);
  };

  public:
  Myclass() {};


   RESULTOBJ MyFunc(int i);
};              
  

// Set error if arg zero.
 RESULTOBJ Myclass::MyFunc(int i)
 {

  if (i==0)
  {
    SetError("My Error"); return pyfail;
  };
       
  return wrap_int(i);

 };



Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote in message news:<mailman.1042464563.14385.python-list at python.org>...
> On Mon, Jan 13, 2003 at 04:37:06AM -0800, Andrew Gregory wrote:
> > 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);
> 
> [..snip..]
> 
> > 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 
> 
> Does:
> 
>     import mymodule
> 
>     try:
>         y = myfunc()
>     except mymodule.Myerror:
>         ...
> 
> do what you want?
> 
> -Andrew.




More information about the Python-list mailing list