1

Whether or not it is a good idea (and it probably is considered bad practice), I sometimes return an Error in python instead of raising it.

def fnA( some_param ):
   # use some_param in complicated thing
   if some_param is None:
      return ValueError( "something went wrong" )

def fnB( param_a ):
   val = fnA( param_a )
   if isinstance( val, Exception ):
      # error path

I have been trying to create a python C extension from a regular module that I have written both as practice and because I think it could benefit from it. To do that, I have been using pybind11. It covers most of my needs, except that. I cannot seem to create a ValueError and return it from C (or C++ in this case).

I have looked at the documentation, at python's own source code and I have not found a way to create an exception without raising it. What I have "found"/tried is this:

auto some_fn() -> PyExc_ValueError* {
   PyObject* type;
   PyObject* value;
   PyObject* traceback;

   PyErr_SetString( PyExc_ValueError, "error in my function !!!" );
   PyErr_Fetch( &type, &value, &traceback );
   PyErr_NormalizeException( &type, &value, &traceback );
   if( traceback != NULL ) {
      PyException_SetTraceback( value, traceback );
   }
   PyErr_Clear();
   return value;
}

which sets the exception, fetches it, normalizes it, clears it and returns the concrete error. I thought it would work but it does not even compile.

Anyone can point me in the right direction for creating and returning an exception in the C API? It might not really be possible, but then again, it is so easy in python code, I have a hard time believing it can't be done.

Thanks in any case.

ghlecl
  • 3,127
  • 1
  • 16
  • 15
  • For a bit of follow-up, I have found a way via pybind. I am importing the ValueError object from the builtins module via py::module_::import("builtins").attr("ValueError"). And then, I call the type with a message and return it. I am still curious how this would be done in the C API, so I am leaving the question open. – ghlecl Dec 05 '21 at 04:46

0 Answers0