[C++-sig] First pass at exception translator template

Gavin Doughtie gdoughtie at anim.dreamworks.com
Tue Jun 3 01:30:00 CEST 2003

So, this is probably gross or non thread-safe in some manner that I'm 
not clued into yet. I'd appreciate any elegant refactorings, but this 
seems to work and will allow me to just specify a bunch of 
"REGISTER_EXCEPTION" lines in my module.

template <typename ExceptionType>
struct ExceptionTranslator
   typedef ExceptionTranslator<ExceptionType> type;

   static PyObject *pyException;

   static void RegisterExceptionTranslator(scope & scope, const char* 
moduleName, const char* name)
     // Add the exception to the module scope
     std::strstream exName;
     exName << moduleName << "." << name << '\0';
     pyException = PyErr_NewException(exName.str(), NULL, NULL);
     handle<> instanceException(pyException);
     scope.attr(name) = object(instanceException);

     // Register a translator for the type
     register_exception_translator< ExceptionType >

   static void translateException(const ExceptionType& ex)
     PyErr_SetString(pyException, ex.getMessage().ptr());

template<typename ExceptionType>
PyObject* ExceptionTranslator<ExceptionType>::pyException;

// Convenience macro
#define REGISTER_EXCEPTION(scopeRef, moduleName, className) \
moduleName, #className)

// Module 

   scope moduleScope;

   REGISTER_EXCEPTION(moduleScope, "my_module", InstanceException);


Gavin Doughtie
DreamWorks SKG

More information about the Cplusplus-sig mailing list