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.


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:

  1. Don't send C++ exceptions up to the Java stack. It'll crash your application. Make sure they're all wrapped in the correct manner. I know you're asking about this but it's really imperative you get that in. One missed exception can hose it all.
  2. Don't try passing Java exceptions down to the C++ stack, they get converted to SWIGDirectorExceptions or SWIGMethodExceptions. It's a real pain because you loose type information on the Java exception. Instead, if you aren't dealing with a director, create a C++ class which does nothing more than raise C++ exceptions so that you can propogate C++ exceptions along the C++ stack.
  3. Wrap all naked strings passed from Java to C++ in a std::string. If you keep them as 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.

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

Here's the macro:

%javaexception(JTYPE) MATCH {
  try {
  catch ( CPPTYPE & e ) {
    jclass eclass = jenv->FindClass(JNITYPE);
    if ( eclass ) {
      jenv->ThrowNew( eclass, e.what() );

Need Your Help

Dropdown menu in a fixed header cut off on mobile

html css drop-down-menu overflow css-position

I'm having troubles with a dropdown menu in a fixed header on mobile. When I hover over a menu item, its submenu opens but I cannot scroll to see the hidden items, although I've put an overflow-y: ...

How to change one image when multiple areas can be clicked

javascript jquery twitter-bootstrap

I have an image on an expandable chat window. Basic plus and minus sign, but what I am getting hung up on is that you can click on two different spots to open the window. Right now when you click...