我正在使用pybind11用python编写代码
例如,我有test1.cpp、test_pybind.cpp和example.py
heaan_pybind.cpp
namespace py=pybind11;
PYBIND11_MODULE(test, m)
{
py::class_<test1>(m, "test1")
.def("fn", ...)
}
在example.py中,我想控制异常,如下所示
import test
while True:
try:
test.test1.fn(...)
except ???:
print("exception error.")
如何从example.py中的test.cpp捕获错误或异常
如果您不知道异常的类型,只需捕获最一般的类型,如
Exception
。见下文微不足道的方法是确保所有要在Python中捕获的C++异常也是绑定的一部分。
因此,在您的模块中,假设您有一个名为
CppExp
的cpp异常类型,您可以执行以下操作这将创建一个名为
PyExp
的新python异常,并将导致抛出CppExp
的任何代码将其重新映射到python异常中然后在python代码中可以执行以下操作
关于异常处理的其他pybind11文档如下: https://pybind11.readthedocs.io/en/master/advanced/exceptions.html
<如果你的C++异常有你想翻译成Python的自定义字段或方法,你必须根据我的答案实际修改pybDun11代码: How can you bind exceptions with custom fields and constructors in pybind11 and still have them function as python exception?相关问题 更多 >
编程相关推荐