Skip to content

Instantly share code, notes, and snippets.

@FZambia
Last active December 13, 2015 22:58
Show Gist options
  • Save FZambia/4987834 to your computer and use it in GitHub Desktop.
Save FZambia/4987834 to your computer and use it in GitHub Desktop.
C Python Division gcc error_handling.cpp -I /usr/include/python2.7/ -lpython2.7 -lstdc++ -o error_handling ./error_handling
#include <Python.h>
#include <iostream>
using namespace std;
int main()
{
Py_Initialize();
PyObject* po_operator = PyImport_ImportModule("operator");
PyObject* po_division = PyObject_GetAttrString(po_operator, "div");
PyObject* po_arg1 = PyInt_FromLong(30);
PyObject* po_arg2 = PyInt_FromLong(1);
PyObject* po_result = PyObject_CallFunctionObjArgs(po_division, po_arg1, po_arg2, NULL);
PyObject* Err = PyErr_Occurred();
if (Err) {
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
char *pStrErrorMessage = PyString_AsString(pvalue);
cout << pStrErrorMessage << endl;
}
else {
long resultstr = PyInt_AsLong(po_result);
cout << resultstr << endl;
}
Py_DECREF(po_arg1);
Py_DECREF(po_arg2);
Py_DECREF(po_division);
Py_DECREF(po_operator);
Py_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment