A feature request, and, Re: [C++-sig] Re: Exception translation to python classes

Lijun Qin qinlj at solidshare.com
Tue Sep 23 03:17:03 CEST 2003


I have the same problem several days ago, and I have found that Python (at
least 2.2) need the exception class derived (directly or indirectly) from
the standard "PyExc_Exception" class, so to use the ideal

PyErr_SetObject(PyExc_MyException,  InstanceOfMyException)
-or in python-
raise mymodule.MyException(arg1, arg2)

form of code, you need to use the PyErr_NewException() API to create a new
exception class derived from PyExc_Exception class. And to create '__init__'
and '__str__' function, you also need to create two method object for two
callable object. I have managed to make it work, but it need a lot of

I this process, I have found that if boost.python can support specifing an
existing Python class as base class (or one of the basses), such as specify
'PyExc_Excetion' as the base class of the generated python class, it'll be a
much simpler life for us.

Lijun Qin

----- Original Message ----- 
From: "Niall Douglas" <s_sourceforge at nedprod.com>
To: <c++-sig at python.org>
Sent: Tuesday, September 23, 2003 7:16 AM
Subject: Re: [C++-sig] Re: Exception translation to python classes

> Hash: SHA1
> On 22 Sep 2003 at 12:50, Mike Rovner wrote:
> > Niall Douglas wrote:
> >
> > > I was wondering if anyone had any experience or could point me to
> > > some example code for translating C++ exceptions by using
> > > PyErr_SetObject to the Boost.Python wrap of the appropriate C++
> > > exception object.
> >
> > I'm not quite sure what are you talking about.
> Ok, an example then:
> FXException is my generic base class for all exceptions. It has
> bindings for Python ie; a FXException is available there too.
> I've registered an exception translator for FXException. If what you
> say below is correct, then it merely needs to be:
> void FXException_translator(const FXException &e)
> {
>     PyErr_SetObject(PyExc_RuntimeError, python::object(e));
> }
> ... and all should be good.
> If so, then my thanks again. This makes error reporting in python
> much more useful indeed as my exception class provides a stack
> backtrace plus line and file info of the C++ side.
> Cheers,
> Niall
> Version: idw's PGP-Frontend / 9-2003 + PGP 8.0.2
> =BGwZ
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig

More information about the Cplusplus-sig mailing list