Raising Exceptions
From DANSE
It's pretty simple to raise an exception, at least most of the time. First, use PyErr_SetString( ) to set the exception indicator. For example, suppose someone has given you an input with a value less than zero, but the input is destined for an unsigned int:
if( argument1 < 0)
{
PyErr_SetString( PyExc_ValueError,
"argument 1 must be >= 0");
return 0; // trigger exception
}
The first argument is the Python error type. Perennial favorites are PyExc_TypeError, PyExc_ValueError, PyExc_IOError, PyExc_RuntimeError. See API documentation for a complete list. The second argument is a C-string (you can always use the c_str() method of a std::string).
If you're not in a regular wrapper where you can just return 0, here are some possibilities. If you're in a function called by a wrapper, can you either return an error signal to the wrapper, or throw an exception that the wrapper can catch? (Careful--is this subroutine used by others?) The hardest case may be in a delete function for a PyCObject. That has void return type, and you can't throw because chances are the exception won't be caught. If worse comes to worse, you can always try the PyErr_WriteUnraisable(); consult the API documentation for more information.
