Skip to content

enhancements cppexceptions

n1ywb edited this page May 4, 2011 · 1 revision

In a perfect world one might translate Pythonic exception handling directly into C++ handling. However the semantics are pretty different and that approach would probably lead to tears. Here's another idea.

Declare your C++ functions thus:

cdef void foo(void) throws (MyException, std.exception, ...)

this might generate C++ code like this

try {
  foo();
}
catch (MyException e) {
  PyObject py_e = MyException(e); // PYTHON MyException; namespace issue here?
  python raise py_e; // Please forgive my ignorance of the Python C API
}
catch (std::exception e) {
  PyObject py_e = std.exception(e);
  python raise py_e; // Please forgive my ignorance of the Python C API
}
catch (...) {
  PyObject py_e = UnknownCPPException();
  python raise py_e;
}

There must be defined a Python wrapper class for std::exception that takes an instance of the latter in it's constructor. The same pattern could apply to custom exception classes; For any c++ exception you want to catch there must be defined a Python wrapper for that class with the same name that takes the C++ object in it's constructor.

While this wouldn't allow serious hacking into the try/catch code, it it would be a huge improvement over the current situation in that you could catch any C++ exception and raise it as a python exception with minimal coding.

Clone this wiki locally