I wrapped a C++ and a custom execption class as described in the answer to question: How do I propagate C++ exceptions to Python in a SWIG wrapper library?
Using my class in Python, calling the function which throws the exception and catching the exception yields the following error:
Traceback (most recent call last):
File "../WrapperTester/src/main.py", line 17, in <module>
ret = cow.milkCow()
File "..\WrapperTester\src\CowLib\CowLib.py", line 115, in milkCow
return _CowLib.Cow_milkCow(self)
src.CowLib.CowLib.CowException: None
This is my C++ class header including the exception:
class CowException {
private:
std::string message = "";
public:
CowException(std::string msg);
~CowException() {};
std::string what();
};
class _Cow
{
private:
int milk;
int hunger;
public:
_Cow();
~_Cow();
int milkCow() throw(CowException);
void feed(int food) throw(CowException);
};
And my SWIG header:
%module CowLib
%include "exception.i"
%include "Cow.i"
%{
#define SWIG_FILE_WITH_INIT
#include "Cow.h"
#include "_Cow.h"
static PyObject* pCowException;
%}
%init %{
pCowException = PyErr_NewException("_CowLib.CowException", NULL, NULL);
Py_INCREF(pCowException);
PyModule_AddObject(m, "CowException", pCowException);
%}
%exception Cow::milkCow {
try {
$action
} catch (CowException &e) {
PyErr_SetString(pCowException, e.what().c_str());
SWIG_fail;
}
}
%exception Cow::feed {
try {
$action
} catch (CowException &e) {
PyErr_SetString(pCowException, e.what().c_str());
SWIG_fail;
}
}
%include "_Cow.h"
%pythoncode %{
CowException = _CowLib.CowException
%}
Where the Header "Cow.i" is the "standard" SWIG-Header:
%module Cow
%{
#include "_Cow.h"
#include "Cow.h"
%}
%include "Cow.h"