Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIG: Reporting Python exceptions from C++ code

I am using a library, which specifies in its API docs to define a class inherited from some particular class of of the library. The library itself is written in C++ and the bindings to Python is generated using SWIG. The problem is, when I run my Python code, no matter what exception Python throws, I get the error saying "terminate called after throwing an instance of 'Swig::DirectorMethodException'".

I would like to have this exception raised by the Python code to be reported while executing my program. Esp, those cases where I get ZeroDivisionError.

I tried to hack a bit by following the method described in the SWIG documentation at http://www.swig.org/Doc2.0/Python.html#Python_nn36 but with no luck. I still get the same message "terminate called after throwing an instance of 'Swig::DirectorMethodException'" no matter what I put in the module.i file.

Can some one please give me pointers on how to go about with this problem, so that Python exceptions are reported as they are?

like image 540
Madhusudan.C.S Avatar asked Jan 26 '11 23:01

Madhusudan.C.S


2 Answers

Report exception raised by Python in the console of the program.

This is the useful fix from Madhusudan.C.S. See his comment on ginbot's answer. I am putting it as an answer so that it becomes more visible.

/* MyInterface.i */
%module(directors="1") MyInterface
%feature("director:except") {
    if( $error != NULL ) {
        PyObject *ptype, *pvalue, *ptraceback;
        PyErr_Fetch( &ptype, &pvalue, &ptraceback );
        PyErr_Restore( ptype, pvalue, ptraceback );
        PyErr_Print();
        Py_Exit(1);
    }
} 
like image 120
LaChocolaterie Avatar answered Nov 04 '22 03:11

LaChocolaterie


I don't know how far along you are with your code base, so this may be of little use, but I had better luck with boost::python than SWIG. Then you could do this: boost::python Export Custom Exception

like image 40
ginbot Avatar answered Nov 04 '22 02:11

ginbot