【问题标题】:Why Python doesn't catch exceptions raised in C++?为什么 Python 不能捕获 C++ 中引发的异常?
【发布时间】:2014-12-05 08:45:48
【问题描述】:

我正在尝试在 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")

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

为什么?

【问题讨论】:

  • 如果底层迭代器是 C++ 迭代器,那么可能值得使用boost::python::iterator,因为它处理所有细微的细节(例如让迭代器延长容器的寿命)。这个answer 演示了它的用法。

标签: python c++ exception python-3.x boost-python


【解决方案1】:

设置 Python 异常后,必须像这样通知 Boost.Python:

throw_error_already_set();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2021-12-26
    • 2014-11-24
    • 1970-01-01
    • 2013-10-26
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多