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.
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
Since I've wrestled with this (see my blog from my profile, it's on python, SWIG, exceptions and directors but should help) let me give you a few pieces of advice:
const char
pointers Java will have the option to garbage collect them. This is true of all items but it's such an easily overlooked one that I've done it and seen it done a few times already. After that, don't read 1.1. Use the documentation from 2.0 or 1.3. It's much more clear.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.