Awasu » Embedding Python: Handling errors
Sunday 30th November 2014 7:58 AM []

In all our examples so far, we haven't really checked for errors, so in this tutorial, we'll take a look at how to do this properly.

In the event of an error, Python will return an error value[1]For example, NULL if the API call normally returns a PyObject*. and it's up to the caller to retrieve the details of what went wrong. We do this by calling PyErr_Fetch(), which returns us the normal Python error variables (sys.exc_type, sys.exc_value and sys.exc_traceback).

// try to parse a bad string as an int
PyObject* pVal = PyInt_FromString( "xyz" , NULL , 10 ) ;
if ( pVal != NULL )
    assert( false ) ; // eek! it should've failed
else
{
    // get the error details
    cout << "An error occurred:" << endl ;
    PyObject *pExcType , *pExcValue , *pExcTraceback ;
    PyErr_Fetch( &pExcType , &pExcValue , &pExcTraceback ) ;
    if ( pExcType != NULL )
    {
        PyObject* pRepr = PyObject_Repr( pExcType ) ;
        cout << "- EXC type: " << PyString_AsString(pRepr) << endl ;
        Py_DecRef( pRepr ) ;
        Py_DecRef( pExcType ) ;
    }
    if ( pExcValue != NULL )
    {
        PyObject* pRepr = PyObject_Repr( pExcValue ) ;
        cout << "- EXC value: " << PyString_AsString(pRepr) << endl ;
        Py_DecRef( pRepr ) ;
        Py_DecRef( pExcValue ) ;
    }
    if ( pExcTraceback != NULL )
    {
        PyObject* pRepr = PyObject_Repr( pExcValue ) ;
        cout << "- EXC traceback: " << PyString_AsString(pRepr) << endl ;
        Py_DecRef( pRepr ) ;
        Py_DecRef( pExcTraceback ) ;
    }
}

And when we run this code, we can see that the int conversion fails as expected, and Python returns us the error information.


Indeed, the same error information as if we did the same thing in a Python interpreter.

Download the source code here.


   [ + ]

1. For example, NULL if the API call normally returns a PyObject*.
Have your say