Saturday, February 24, 2007

Language independent exception handling on SWIG

This is quite useful when wrapping code using SWIG for several languages. By adding this snippet to my interface definition file:

// Language independent exception handler
%include exception.i

%exception {
try {
} catch(string& stringReason) {
const char* sData = (char*)stringReason.c_str();
} catch(...) {
SWIG_exception(SWIG_RuntimeError,"Unknown exception");

I can do this on C++:

if (dbSpace.count(dbId)) {
throw string("dbId already in use");

and catch native runtime exceptions on Python or Java:

except RuntimeError, e:
print e

>> dbId already in use

No comments: