exceptions from C

Mitchell Morris mgm at unpkhswm04.bscc.bls.com
Wed Nov 3 13:08:47 EST 1999


Ordinarily I would sneer at your puny spam-trapped return address, but you
didn't ask for an email followup. Good for you!

In article <Pine.LNX.4.10.9911040950440.25629-100000 at crb.crb-web.com>,
Linux User wrote:
>I have been reading the section in the Lutz book on exceptions.  It seems
>that exceptions are no longer simply string objects.  Does this change the way
>exception are raised from C?  If so where might I find info on how to do this?
>
>Thanks,
>Wayne

I must admit I haven't look at my Lutz book in a while. Mea culpa.

You can find several examples of raising exceptions in the source distribution,
in the Demo directory. To raise one of the system exceptions, it's super-
easy:

	...
	if(some-test-failed) {
		PyErr_SetString(PyExc_KeyError, "bad dog! no biscuit!");
		return NULL;
	}
	...


To raise an exception already defined in a module, it's slightly more
complicated:

	PyObject* module = PyImport_AddModule("mymodule");
	PyObject* dict = PyModule_GetDict(module);
	PyObject* myexc = PyDict_GetItemString(dict, "MyException");
	// myexc is a borrowed reference ... don't decrement the count!
	PyErr_SetString(myexc, "bad dog! no biscuit!");



Finally, if you want to define the exception within the C++ part instead of
in the Python part:

	PyObject* module = PyImport_AddModule("mymodule");
    PyObject* dict = PyModule_GetDict(module);
    MYSTUFF_DataException = PyErr_NewException("MYSTUFF.DataException",
                                               NULL, NULL);
    PyDict_SetItemString(dict, "DataException, MYSTUFF_DataException);

and then use the code snippet above to raise it.


<exceptioning-for-fun-and-profit-ly y'rs>
+Mitchell


-- 
Mitchell Morris

My mind is like a steel trap - rusty and illegal in 37 states.
	-- Carrie Fish




More information about the Python-list mailing list