title: Dynamically rethrowing self-defined C++ exceptions as Python exceptions using SWIG
body: <p><strong>Situation</strong></p>
  
  <p>I want to create a Python language binding for a C++ API using SWIG. Some of the API functions may throw exceptions. The C++ application has a hierarchy of self-defined exceptions, like this example:</p>
  
  <pre><code>std::exception
    -&gt; API::Exception
      -&gt; API::NetworkException
        -&gt; API::TimeoutException
        -&gt; API::UnreachableException
      -&gt; API::InvalidAddressException
  </code></pre>
  
  <p>The desired behavior is as follows:</p>
  
  <ol>
  <li><p>All exception types should have a matching Python class as <strong><em>wrapper</em></strong>. These wrapper classes should be <strong><em>valid Python exceptions</em></strong>. </p></li>
  <li><p>When an API call throws a <strong><em>C++ exception</em></strong>, it should be <strong><em>caught</em></strong>. The <strong><em>corresponding Python exception</em></strong> (i.e. the wrapper class of the caught C++ exception) should be <strong><em>thrown</em></strong>.</p></li>
  <li><p>This should be a dynamic process: the Python <strong><em>exception type is decided at runtime</em></strong>, only based on the runtime type of the caught C++ exception. This way, there is no need to describe the complete exception hierarchy in the SWIG interface file.</p></li>
  </ol>
  
  <p><strong>Problems and questions</strong></p>
  
  <ol>
  <li><p>Wrapper classes are no Python exceptions.</p>
  
  <p>While SWIG creates wrapper classes for all self-defined exceptions (like for any other class), these classes are not Python exceptions. The wrapper of the base exception (<code>API::Exception</code> in the example) extends <code>Object</code> instead of <code>BaseException</code>, the Python class of which all exceptions in Python should be derived.</p>
  
  <p>Furthermore, it doesn't seem possible to let SWIG add a parent class manually. Note this is possible when using SWIG with Java through the usage of <code>%typemap(javabase)</code> (see <a href="http://www.swig.org/Doc2.0/Java.html#Java_code_typemaps">SWIG documentation</a> for details).</p></li>
  <li><p>How can the <a href="http://docs.python.org/2/c-api/">Python C API</a> throw a user-defined exception?</p>
  
  <p>The most common way to throw a Python exception from the Python C API is by calling <code>PyErr_SetString</code> <a href="http://docs.python.org/2/c-api/exceptions.html#PyErr_SetString">[reference]</a>. This is also shown in the demo application below.</p>
  
  <p>But this is only trivial with the standard (built-in) exceptions of Python, because references to them are stored in global variables [<a href="http://docs.python.org/2/c-api/exceptions.html#standard-exceptions">reference</a>] in the Python C API. </p>
  
  <p>I know there is a method <code>PyErr_NewException</code> <a href="http://docs.python.org/2/c-api/exceptions.html#PyErr_NewException">[reference]</a> to get references to self-defined exceptions, but I didn't got this working.</p></li>
  <li><p>How can the <a href="http://docs.python.org/2/c-api/">Python C API</a> evaluate the C++ type at runtime and then find the corresponding Python wrapper class by name?</p>
  
  <p>I assume a Python class can be searched by name at runtime, through the <a href="http://docs.python.org/2/c-api/reflection.html">reflection part</a> of the Python C API. Is this the way to go? And how is it done in practice?</p></li>
  </ol>
  
  <p><strong>Demo application</strong></p>
  
  <p>To experiment with this problem, I created a tiny C++ API with a single function that calculates the factorial of a number. It has a minimal self-defined exception hierarchy, consisting of only one class <code>TooBigException</code>. </p>
  
  <p>Note this exception acts as the base exception in the general problem and the application should work with any subclass of it. This means the solution may only use the dynamic (i.e. runtime) type of the caught exception to rethrow it in Python (see below).</p>
  
  <p>The full source code of the demo application is as follows:</p>
  
  <pre><code>// File: numbers.h
  namespace numbers {
  int fact(int n);
  }
  
  // File: numbers.cpp
  #include "TooBigException.h"
  namespace numbers {
  int fact(int n) {
      if (n &gt; 10) throw TooBigException("Value too big", n);
      else if (n &lt;= 1) return 1;
      else return n*fact(n-1);
  }
  }
  
  // File: TooBigException.h
  namespace numbers {
  class TooBigException: public std::exception {
  public:
      explicit TooBigException(const std::string &amp; inMessage,
                               const int inValue);
      virtual ~TooBigException() throw() {}
      virtual const char* what() const throw();
      const std::string &amp; message() const;
      const int value() const;
  private:
      std::string mMessage;
      int mValue;
  };
  }
  
  // File: TooBigException.cpp
  #include "TooBigException.h"
  namespace numbers {
  TooBigException::TooBigException(const std::string &amp; inMessage, const int inValue):
      std::exception(),
      mMessage(inMessage),
      mValue(inValue)
  {
  }
  const char* TooBigException::what() const throw(){
      return mMessage.c_str();
  }
  const std::string &amp; TooBigException::message() const {
      return mMessage;
  }
  const int TooBigException::value() const {
      return mValue;
  }
  }
  </code></pre>
  
  <p>To get the Python binding I use the following SWIG interface file:</p>
  
  <pre><code>// File: numbers.i
  %module numbers
  %include "stl.i"
  %include "exception.i"
  
  %{
  #define SWIG_FILE_WITH_INIT
  #include "TooBigException.h"
  #include "numbers.h"
  %}
  
  %exception {
      try {
          $action
      }
      catch (const numbers::TooBigException &amp; e) {
          // This catches any self-defined exception in the exception hierarchy,
          // because they all derive from this base class. 
          &lt;TODO&gt;
      }
      catch (const std::exception &amp; e)
      {
          SWIG_exception(SWIG_RuntimeError, (std::string("C++ std::exception: ") + e.what()).c_str());
      }
      catch (...)
      {
          SWIG_exception(SWIG_UnknownError, "C++ anonymous exception");
      }
  }
  
  %include "TooBigException.h"
  %include "numbers.h"
  </code></pre>
  
  <p>So every call to the API is wrapped by a try-catch block. First exceptions of our base type are caught and handled. Then all other exceptions are caught and rethrown using the SWIG exception library.</p>
  
  <p>Note any subclass of <code>numbers::TooBigException</code> is caught and the <strong><em>wrappers of their dynamic (i.e. runtime) type should be thrown</em></strong>, not the wrapper of their static (i.e. compile time) type, which is always <code>TooBigException</code>!</p>
  
  <p>The project can be built easily by executing the following commands on a Linux machine:</p>
  
  <pre><code>$ swig -c++ -python numbers.i
  $ g++ -fPIC -shared TooBigException.cpp numbers.cpp numbers_wrap.cxx \
      -I/usr/include/python2.7 -o _numbers.so
  </code></pre>
  
  <p><strong>Current implementation</strong></p>
  
  <p>My current implementation still (successfully) throws a fixed standard Python exception. The code <code>&lt;TODO&gt;</code> above is then replaced by:</p>
  
  <pre><code>PyErr_SetString(PyExc_Exception, (std::string("C++ self-defined exception ") + e.what()).c_str());
  return NULL;
  </code></pre>
  
  <p>Which gives the following (expected) behavior in Python:</p>
  
  <pre><code>&gt;&gt;&gt; import numbers
  &gt;&gt;&gt; fact(11)
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  Exception: C++ self-defined exception Value too big
  </code></pre>