user2881627
user2881627

Reputation: 41

How to catch Python exception thrown in C++ code wrapped in a boost python module

I have C++ code wrapped in a boost python module.

My C++ code does something like this:

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

i.e. it attempts to create a boost Python string from a C string that contains an unprintable character (value 160).

When I run this code from Python script, I get this error:

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

which occurs as value 0xa0 (= 160) cannot be decoded.

How can I catch this error in the C++ code?

Upvotes: 2

Views: 284

Answers (1)

John Zwinck
John Zwinck

Reputation: 249123

Like this:

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

There's no information available from the exception type error_already_set - it is named this way because it means that the error is set inside the Python interpreter state.

Upvotes: 2

Related Questions