如何捕获包含在 boost python 模块中的 C++ 代码中抛出的 Python 异常

问题描述

我将 C++ 代码封装在一个 boost python 模块中。

我的 C++ 代码做了这样的事情:

char s[2];
s[0] = (char) 160;
s[1] = '\0';
boost::python::str bs = boost::python::str(s);

即它尝试从包含不可打印字符(值 160)的 C 字符串创建一个 boost Python 字符串。

当我从 Python 脚本运行此代码时,出现此错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 11: invalid start byte

出现值 0xa0 (= 160) 无法解码。

如何在 C++ 代码中捕获此错误

解决方法

像这样:

boost::python::str bs;
try
{
    bs = boost::python::str(s);
}
catch (const boost::python::::error_already_set&)
{
    PyErr_Clear();
}

异常类型 error_already_set 中没有可用信息 - 它以这种方式命名是因为这意味着错误是在 Python 解释器状态中设置的。