Mizux/cmake-swig

Exception support

romainreignier opened this issue · 6 comments

Thank you for this nice work!

I was wondering if you ever tried to propagate exceptions from C++ to the other languages?
This may be added to this example.

Mizux commented

Good question !
To be honest, at Google, C++ exceptions are forbidden so I never dig into this topic, however AFAIK SWIG provide some macros (i.e. tooling) to deal with exceptions forwarding could be fun to give it a try once I have time to work on it ^^.

Ok, I see.

I have tried it by adding

%include "std_except.i"

And manually adding the catches keyword for method definition:

%catches(std::runtime_error) MyLib::my_method();

It works on Python and map to a RuntimeError.

But I was wondering if there is another method.

Mizux commented

According to the doc

Exceptions are automatically handled for methods with an exception specification. Similar handling can be achieved for methods without exception specifications through the %catches feature.

Mizux commented

looking at the swig code:
https://github.com/swig/swig/blob/master/Lib/typemaps/std_except.swg
and
https://github.com/swig/swig/blob/master/Lib/typemaps/exception.swg

swig should be able to catch most standard exceptions hope to play with it soon !

e.g. adding in C++ Foo class a method:

void letsThrow(int idx) {
  switch (idx) {
    case 1:
      throw std::runtime_error("runtime error");
   case 2: 
   ...
  } 
}

and in foo.i

%include exception.i

 %exception {
    try {
      $action
    }
    SWIG_CATCH_STDEXCEPT // catch std::exception
    catch (...) {
     SWIG_exception_fail(SWIG_UnknownError, "Unknown exception");
    }
  }

%feature("except")

foo::letsThrow(int);

and see what's happen 😄 when called from Python/Java/.Net

Oh, this snippet seems great! It avoids to declare a %catches statement for each method.
To make it work, I had to remove the line:

%feature("except")