为什么 Python 没有捕获C++中引发的异常?

Why Python doesn't catch exceptions raised in C++?

本文关键字:异常 C++ Python 为什么      更新时间:2023-10-16

我正试图在boost::Python中制作一个Python迭代器。所以我有一个功能

PyObject *my_iterator_next(MyIterator *iter) {
    if (!iter->is_end()) {
        return *(*iter)++;
    }
    else {
        PyErr_SetNone(PyExc_StopIteration);
        // this doesn't work either
        // PyErr_SetString(PyExc_StopIteration, "end of collection");
        return NULL;
    }
}

在Python中:

// x is MyContainer([1, 2, 3])
for x in my_container:
    print(x)

我得到:

1
2
3
NoneTraceback (most recent call last):
  File "main.py", line 6, in <module>
    print(x)
StopIteration: end of collection

还有

it = my_collection.__iter__()
try:
    it.__next__();
    it.__next__();
    it.__next__();
    it.__next__();
except:
    print("caught exception")

此代码不打印任何内容,因此不会捕获任何类型的异常。

为什么?

设置Python异常后,必须通知Boost.Python如下:

throw_error_already_set();

请参阅http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/errors.html