[vtk-developers] Robustifying the JNI

Brad King brad.king at kitware.com
Tue Oct 11 10:03:17 EDT 2005


Steve M. Robbins wrote:
> My colleague and I spent Friday modifying the java wrapper code with
> an eye to making it less likely to bring down the JVM.  We'd like to
> contribute this code to VTK so please criticize this proposal.
> 
> The first thing we did was wrap each JNI function inside a 
> try/catch block:

This change was made to the Tcl wrappers recently so there is no problem 
with doing it for Java too.  I don't think there are any supported 
compilers that don't have exceptions so you don't even need an #if 
arround it.  However we only catch std::exception and subclasses:

   try
     {
     ...
     }
   catch (vtkstd::exception &e)
     {
     // transform to language-specific error or exception
     }

The idea is that all standard library and user exceptions should derive 
from this and be caught.  Other system-level exceptions (such as abort 
or segfault on some platforms) are let through so that they can be 
caught by a debugger.

> We also wondered about the lack of exceptions in VTK.  Is it because
> of obscure compilers in use in 2005?  Or, rather, due to the state of
> exception handling in the early 90s when VTK got its start?  Is it now
> acceptable to introduce exceptions?  If not in mainline code, then
> at least in JNI code?  Presumably anyone wrapping it for java is using
> a compiler that knows about exceptions.

Lack of exceptions in VTK is due to historical reasons.  We cannot 
introduce them because way too much of the code was not written with 
exception safety in mind and will leak resources when an exception 
unwinds the stack.

You are free to introduce them inside the JNI code so long as they can 
never propagate through code not aware of them or back into the java 
runtime.  Catching them and translating them into native java exceptions 
is a good idea.

> The main reason to throw an exception rather than test the return
> value is that there are a zillion callers to
> vtkJavaGetPointerFromObject(), not all of which are generated by
> vtkWrapJava.  It's way less error-prone to check return values in this
> one method than audit all its callers.
> 
> 
> Also we fixed the vtkJavaMakeJArrayOfXFromY() methods to
> throw if the array could not be created.
> 
> 
> Finally, here are the methods for throwing java exceptions.  Note
> that the first exception thrown wins.  This allows us to set an
> exception deep in the bowels of vtkJavaGetPointerFromObject(),
> then throw to unwind the stack without fear of the catch(...)
> clause overwriting the exception set.

This looks fine to me.  Just make sure the unwinding meets the weak 
exception guarantee (no resources leaked, objects left in a valid state).

-Brad



More information about the vtk-developers mailing list