[英]Catch C++ exceptions in cython
这两天我无法解决这个问题。 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. (如果重要的话,我在 Windows 上)
我设法在 python 中捕获了手动抛出的异常,但我无法捕获 c++ 代码中生成的零除错误或堆栈溢出错误,我错过了什么?
使用:Python 3.6.4 和 Cython 0.29.21
构建和启动命令: python setup.py build_ext --inplace && python main.py
异常.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;
}
};
测试.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)
安装程序.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("test.pyx"),)
主文件
#!/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())
由于您使用的是 Windows,如果您使用的是 VS C++ 编译器,您可以设置异常处理标志以启用 SEH 异常,如下所示: /EHa
这将允许它捕获“硬”异常,例如除以零。 然后在 Python 你会看到:
...
RuntimeError: Unknown exception
这并不理想,但仍然比无声的崩溃要好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.