[C++-sig] How to create a custom exception derived from Exception

Jim Bosch talljimbo at gmail.com
Thu Aug 2 05:28:21 CEST 2012


On 08/01/2012 09:07 AM, Glenn Ramsey wrote:
> On 31/07/12 22:58, Jim Bosch wrote:
>> On 07/31/2012 06:14 PM, Glenn Ramsey wrote:
>>>
>>> Using boost::python how can I create an a custom exception that is
>>> derived from Python's Exception? The functionality I would like to get
>>> by doing this is to provide additional methods for the catching code to
>>> retrieve information from the exception.
>>>
>>
>> The approach I've taken in the past (sorry, don't have an example
>> right now) is
>> to raise a true Python exception (from PyErr_NewException), and attach
>> your
>> Boost.Python-wrapped C++ exception to it as an instance variable.
>> Then put a
>> __getattr__ in the true Python exception that forwards to the
>> Boost.Python
>> object it holds.
>>
>> I can try to reconstruct more details if needed, but hopefully that's
>> enough to
>> get you started.
>
> Thanks, based on that I have done this, which seems to work, but I'm not
> sure if it is entirely correct. I didn't need to implement __getattr__
> and would be interested in seeing some more details of your approach.
>

Looks fine to me.  I'm afraid I don't really have any more details - I 
last did this a while ago, and I don't exactly remember where it was 
anymore.  But it seems pretty similar to what I did.

Jim




More information about the Cplusplus-sig mailing list