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

北城以北 提交于 2019-12-19 19:45:24

问题


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 and I saw this catch (error_already_set const &)

I read the boost docs but it explains where it is used. But I want to know why it is needed and how can I achieve the same functionality using the native Python C api.


回答1:


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<PyObject> 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).



来源:https://stackoverflow.com/questions/43094001/what-does-error-already-set-in-boost-python-do-and-how-to-handle-exceptions-simi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!