Python exception text on syntax errors (boost library)
I've got this code snnipet (the whole program compiles and links correctly):
...
t开发者_运维百科ry
{
boost::python::exec_file(
"myscript.py", // this file contains a syntax error
my_main_namespace,
my_local_namespace
);
return true;
}
catch(const boost::python::error_already_set &)
{
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
// the next line crashes on syntax error
std::string error = boost::python::extract<std::string>(pvalue);
...
}
The file that the program tries to execute has a syntax error, so an exception is thrown. When the program tries to get the error message crashes...
The code works well with run-time errors but somehow crashes with syntax errors.
How can i get the error string with this kind of errors?
Thanks in advance
From the documentation of PyErr_Fetch: "The value and traceback object may be NULL even when the type object is not". You should check whether pvalue is NULL or not before trying to extract the value.
std::string error;
if(pvalue != NULL) {
error = boost::python::extract<std::string>(pvalue);
}
If you want to check whether the exception is a SyntaxError you can compare ptype against the exception types listed here.
To answer anymore specifically I would need a backtrace from the point where it crashed.
Edit
pvalue is an exception object, not a str instance so you should use PyObject_Str to get the string representation of the exception.
You may need to call PyErr_NormalizeException first to turn pvalue into the correct exception type.
精彩评论