How to catch the exception from C++ in python via pybind11?

1 c++ python pybind11

I am making code in python using pybind11.

For example, I have test1.cpp, test_pybind.cpp and example.py

heaan_pybind.cpp

namespace py=pybind11;
PYBIND11_MODULE(test, m)
{
  py::class_<test1>(m, "test1")
  .def("fn", ...)
}
Run Code Online (Sandbox Code Playgroud)

And in example.py, I want to control the exception like below.

import test
while True:
  try:
    test.test1.fn(...)
  except ???:
    print("exception error.")
Run Code Online (Sandbox Code Playgroud)

如何在 example.py 中从 test.cpp 中捕获错误或异常?

Jes*_*e C 5

简单的方法是确保您想要在 python 中捕获的所有 c++ 异常也是您的绑定的一部分。

所以在你的模块中,假设你有一个名为 cpp 的异常类型,CppExp你会做类似的事情

namespace py=pybind11;
PYBIND11_MODULE(test, m)
{
  py::register_exception<CppExp>(module, "PyExp");
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个新的python异常调用PyExp,它将导致任何抛出的代码将CppExp其重新映射到python异常中。

然后在你的python代码中你可以做

import test
while True:
  try:
    test.test1.fn(...)
  except test.PyExp as ex:
    print("exception error.", ex)
Run Code Online (Sandbox Code Playgroud)

关于异常处理的其他 pybind11 文档在这里:https ://pybind11.readthedocs.io/en/master/advanced/exceptions.html

如果您的 c++ 异常具有要转换为 python 的自定义字段或方法,则必须按照我在此处的回答实际修改 pybind11 代码: 如何将异常与 pybind11 中的自定义字段和构造函数绑定,并且仍然具有它们的功能蟒蛇异常?