it's two days I cannot get around this problem. In the following code I am trying to generate uncaught exceptions in C++ code, wrap the C++ code in cython and cal the class methods in a python script. (I am on Windows if that matters)
I managed to catch, in python, the exceptions thrown by hand but in no way I can manage to catch zero division error or the stack overflow error generated in the c++ code, what am I missing?
Using: Python 3.6.4 and Cython 0.29.21
Build and launch command: python setup.py build_ext --inplace && python main.py
exceptions.h
#include <stdexcept>
#include <iostream>
#include <string>
using std::cout;
// Integer division, catching divide by zero.
inline int intDivEx (int numerator, int denominator) {
if (denominator == 0)
throw std::overflow_error("Divide by zero exception");
return numerator / denominator;
}
class exceptions {
public:
void recursion_throw(int stack) {
cout << "\t " << stack;
// this->recursion(stack+1);
if (stack<1000) this->recursion(stack+1);
else {
throw std::overflow_error("My Stackoverflow ERROR!");
}
}
double division_throw(int value) {
int ret_value = 0;
try { ret_value = intDivEx(1, value); }
catch (std::overflow_error e){
cout << e.what() << " value: ";
}
std::cout << value << std::endl;
return 0;
}
void recursion(int stack) {
cout << "\t " << stack;
this->recursion(stack+1);
}
double division(int value) {
int ret_value = 0;
ret_value = 1/value;
return ret_value;
}
};
test.pyx
# distutils: language = c++
import cython
from libcpp.string cimport string
cdef extern from "exceptions.h":
cdef cppclass exceptions:
void recursion_throw(int stack) except +
double division_throw(int value) except +
void recursion(int stack) except +
double division(int value) except +
cdef class Exceptions:
cdef exceptions excps
def recursion(self):
print("Running recursion")
self.excps.recursion(0)
def division(self, value):
print("Running division")
try:
return self.excps.division(value)
except Exception as e:
print(e)
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("test.pyx"),)
main.py
#!/usr/bin/env python
import test
import traceback
if __name__ == '__main__':
S = test.Exceptions()
S.division(0)
try:
S.recursion()
except RuntimeError as e:
print()
print(traceback.format_exc())