Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exception support #7

Open
romainreignier opened this issue Jun 17, 2020 · 6 comments
Open

Exception support #7

romainreignier opened this issue Jun 17, 2020 · 6 comments
Assignees

Comments

@romainreignier
Copy link

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
Copy link
Owner

Mizux commented Jun 17, 2020

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 ^^.

@romainreignier
Copy link
Author

romainreignier commented Jun 17, 2020

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
Copy link
Owner

Mizux commented Jun 17, 2020

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.

@romainreignier
Copy link
Author

romainreignier commented Jun 17, 2020 via email

@Mizux
Copy link
Owner

Mizux commented Jun 17, 2020

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

@romainreignier
Copy link
Author

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")

@Mizux Mizux self-assigned this Nov 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants