[C++-sig] export custom C++ exception to Python so it can beraisedbypython

Giuseppe Corbelli giuseppe.corbelli at copanitalia.com
Wed Nov 7 10:32:28 CET 2012


On 07/11/2012 09:24, Martin Hellmich wrote:
>> *) As you were writing before, declare a C++ class MyException: public
>> std::exception {
>> MyException();
>> MyException(int code, const std::string &string);
>>
>> int code();
>> const char* what();
>>
>> int errorCode;
>> std::string errorMessage;
>> };
>> *) Wrap it as a bpy::class_ so you can use it like a standard exception
>> with all the attributes you need.
>
> This is the part that I miss, I guess. How can I wrap a class so that it works
> like an exception in python? In the solutions on stackoverflow the translation
> to an exception only happens in the translator, meaning that I cannot call
> 'raise MyException' in python, as it doesn't inherit from (the python) Exception.

I've had a closer look. What if we take WindowsError as an example?
*) Define a new python exception CustomError with python/C APIs based on 
WindowsError
*) Define a new C++ exception CustomException based on std::exception
*) Register a translator from C++ to python using CustomError as a target

Seems a reasonable approach.

-- 
             Giuseppe Corbelli
WASP Software Engineer, Copan Italia S.p.A
Phone: +390303666318  Fax: +390302659932
E-mail: giuseppe.corbelli at copanitalia.com


More information about the Cplusplus-sig mailing list