Try/catch does not work with error_already_set

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Try/catch does not work with error_already_set

Christian O'Reilly
This post has NOT been accepted by the mailing list yet.
Hi,

I can't find how or why I can't catch the error_already_set exception. For exemple, the following code

try
{

        exec("3 * 4");

}

catch(...)

{

        cout << "Error" << endl;

}


will not catch the exception and will terminate the program with a error message "terminate called throwing an instance of 'boost::python::error_already_set'". A simple


try
{

        throw runtime_error("Exception occured");

}

catch(...)

{

        cout << "Error" << endl;

}


doed print "Error" as expected. Does anyone has a clue on what might be the problem or how to find the cause of this? I'm compiling under Windows 7 using QT Creator, MinGW 4.6, boost 1.51, and python 2.6.

Thank you for any insights...

Christian
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Try/catch does not work with error_already_set

Christian O'Reilly
This post has NOT been accepted by the mailing list yet.
Ok... I found how to deal with this situation. For those who read these lines and who are as lost as I was, here is a way to handle errors in this situation (adapted from the embedding.cpp boost example file). First I define this function (which I find convinient):

bool handled_exec(str code, object globals = object(), object locals = object())
{
    return handle_exception(boost::bind(exec, code, globals, locals));
}



And then the following code can be used (no need to try/catch):

// Retrieve the main module
object main = import("__main__");

// Retrieve the main module's namespace
object global(main.attr("__dict__"));

string somePythonCode("3 * 4");

if(handled_exec(somePythonCode.c_str(), global, global))
{
      if (PyErr_Occurred())
      {
           PyErr_Print();
      }
      else
      {
           BOOST_ERROR("A C++ exception was thrown  for which "
                                 "there was no exception translator registered.");
      }
}

Happy coding,

Christian
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Try/catch does not work with error_already_set

athieka
This post has NOT been accepted by the mailing list yet.
In reply to this post by Christian O'Reilly
Thank you verymuch.I encountered the same problem. I think this is a bug of mingw.
Loading...