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 {
$action
} catch(string& stringReason) {
const char* sData = (char*)stringReason.c_str();
SWIG_exception(SWIG_RuntimeError,sData);
} 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:


try:
myObject.doSomething(3)
except RuntimeError, e:
print e

>> dbId already in use

No comments: