6

If I have C++ code with embedded Python functions, i.e. it uses Python's C API to call Python's interpreter, how can I get Python exceptions to bubble up to the C++ level?


Note: This is not the inverse question (about propagating C++ extension exceptions up to the Python intepreter).

Will
  • 4,241
  • 4
  • 39
  • 48
  • Depending on your needs, you can just throw the class name of the python exception. Or are you asking how to even access in c++ the exception from the python call. – amwinter Jun 06 '14 at 20:59
  • 1
    The Python exceptions being thrown contain informative messages, which I would like to print in the same way they are printed to the console in pure Python. – Will Jun 06 '14 at 21:00
  • wait, so are you asking how to print the formatted traceback? Or just the exception itself. I think `Py_Print` with the `PyObject*` for the exception should do the latter. – amwinter Jun 06 '14 at 21:02
  • Either one - I'm just not clear on how to get a reference to the exception object in the first place. – Will Jun 06 '14 at 21:03

1 Answers1

1

https://docs.python.org/2/c-api/exceptions.html

specifically, PyErr_PrintEx(0) -- this will print a traceback.

amwinter
  • 3,121
  • 2
  • 27
  • 25
  • 1
    Actually, I'm wondering now if this is wrong. If you're using Py_Main or PyRun_*, it's likely you can't use PyErr_* to access exception info. – amwinter Jun 06 '14 at 21:47
  • I think the OP means "how do I throw a C++ exception with the information in the Python exception?". At least, trying to find out how to exactly that is how I ended up here. – Átila Neves Mar 22 '21 at 14:17