What does error_already_set in Boost.python do and how to handle exceptions similarly in Python C API

前端 未结 1 1943
悲哀的现实
悲哀的现实 2021-01-18 08:20

I have been working on a project where I want to remove the boost dependencies and replace it with the Python C API.

I spent some time understanding the Python C API

1条回答
  •  礼貌的吻别
    2021-01-18 09:10

    Boost throws error_already_set when a Python error has occurred. So if you see code like this:

    try {
        bp::exec(bp::str("garbage code is garbage"));
    } catch (const bp::error_already_set&) {
        // your code here to examine Python traceback etc.
    }
    

    you'll replace it with:

    your_ptr res = PyRun_String("garbage code is garbage");
    if (!res) {
        // your code here to examine Python traceback etc.
    }
    

    In other words, wherever you see catch(error_already_set), there you will likely want to do some error handling using whatever PyObject* or other value is involved to recognize when an error has occurred (and therefore you can examine the traceback, or convert it into a C++ exception).

    0 讨论(0)
提交回复
热议问题