6

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?

Madhusudan.C.S
  • 831
  • 1
  • 7
  • 19

2 Answers2

4

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);
    }
} 
LaChocolaterie
  • 161
  • 2
  • 10
1

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

Community
  • 1
  • 1
ginbot
  • 303
  • 2
  • 6
  • 1
    Thanks for the help. I actually fixed this problem and the fix is here: https://github.com/madhusudancs/mesos/commit/93ed9f32d8752d687d6b6af6bcb6bfdf815f115d It was quite simple, but definitely not well documented. Also, this is not my project, so I can only suggest the developers to use boost::python, but I cannot make it happen though – Madhusudan.C.S Jun 15 '11 at 04:11
  • I figured SWIG was mandatory; I wanted to leave the boost option to people that stumbled upon this question like me :). And now they have the SWIG one as well. – ginbot Jun 15 '11 at 17:06