Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions from C++ via SWIG to Java

We are implementing a wrapper on C++ code for exposure to Java clients. I have seen the SWIG documents about exception handling but what does this translate to in coding terms in the three layers (C++/SWIG/Java)?

If anybody has working example(s) or advice, I would be grateful.

like image 943
Steve Townsend Avatar asked Sep 28 '10 00:09

Steve Townsend


1 Answers

See also in the Swig 2.0 documentation this Java-specific section on exception handling.

To avoid writing the pattern more than once, I created a SWIG macro supporting methods that throw one type of C++ exception -- by catching that and throwing a corresponding Java exception:

WRAP_THROW_EXCEPTION( myCppDeclaration, com::foo::MyCppExceptionClass, 
  "com.foo.MyException",
  "com/foo/MyException" );

Here's the macro:

%define WRAP_THROW_EXCEPTION( MATCH, CPPTYPE, JTYPE, JNITYPE )
%javaexception(JTYPE) MATCH {
  try {
    $action
  }
  catch ( CPPTYPE & e ) {
    jclass eclass = jenv->FindClass(JNITYPE);
    if ( eclass ) {
      jenv->ThrowNew( eclass, e.what() );
    }
  }
}
%enddef
like image 111
Andy Thomas Avatar answered Oct 20 '22 22:10

Andy Thomas