1

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", ...)
}

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

import test
while True:
  try:
    test.test1.fn(...)
  except ???:
    print("exception error.")

How can I catch the error or exception from test.cpp in example.py ?

Trivial.SNG
  • 11
  • 1
  • 2

2 Answers2

10

The trivial way is to just make sure all the c++ exceptions you want to catch in python are also part of your bind.

So in your module, assuming you have a cpp exception type called CppExp you would do something like

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

that will create a new python exception called PyExp and it will cause any code that throws CppExp to remap it into the python exception.

Then in your python code you can do

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

additional pybind11 docs on exception handling are here: https://pybind11.readthedocs.io/en/master/advanced/exceptions.html

If your c++ exception has custom fields or methods that you want to translate into python, you will have to actually modify the pybind11 code as per my answer here: How can you bind exceptions with custom fields and constructors in pybind11 and still have them function as python exception?

Jesse C
  • 779
  • 4
  • 11
0

If you don't know the type of exception, simply you can catch the most general type such as Exception. See below

import test
while True:
  try:
    test.test1.fn(...)
  except Exception:
    print("exception error.")
leminhnguyen
  • 1,518
  • 2
  • 13
  • 19