Next: , Previous: Mixing with C++, Up: About CNI

12.14 Exception Handling

While C++ and Java share a common exception handling framework, things are not yet perfectly integrated. The main issue is that the run-time type information facilities of the two languages are not integrated.

Still, things work fairly well. You can throw a Java exception from C++ using the ordinary throw construct, and this exception can be caught by Java code. Similarly, you can catch an exception thrown from Java using the C++ catch construct.

Here is an example:

     if (i >= count)
        throw new java::lang::IndexOutOfBoundsException();

Normally, G++ will automatically detect when you are writing C++ code that uses Java exceptions, and handle them appropriately. However, if C++ code only needs to execute destructors when Java exceptions are thrown through it, GCC will guess incorrectly. Sample problematic code:

     struct S { ~S(); };
     extern void bar();    // Is implemented in Java and may throw exceptions.
     void foo()
       S s;

The usual effect of an incorrect guess is a link failure, complaining of a missing routine called __gxx_personality_v0.

You can inform the compiler that Java exceptions are to be used in a translation unit, irrespective of what it might think, by writing #pragma GCC java_exceptions at the head of the file. This #pragma must appear before any functions that throw or catch exceptions, or run destructors when exceptions are thrown through them.