What is the correct way python memory management in case of exceptions?

Samvel Hovsepyan

I am writing my own Python module and need some advice. Let's consider an example function in a module:

PyObject* my_func(PyObject *self, PyObject* args)
{
    PyObject* returnObj;
    try
    {
       returnObj = my_create_output();
    }
    catch(const std::exception& ex)
    {
        PyErr_SetString(PyExc_Exception, ex.what());
        returnObj = NULL;
    }
    return returnObj;
}

my_create_output function can raise different exceptions (also my own exceptions). returnObj is a big structure (for example, a list) and it may happen that my_create_output function will raise an exception when half of the output is already created. How should I delete the allocated objects in the catch block for such cases?

user2357112 supports Monica

my_create_output should handle the deallocation of everything it creates in the case of an exception, as a caller catching the exception has no way to access any of it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive