Category: Proxy usage

Q

How do I handle Java exceptions in .NET?

A

You can handle Java exceptions through their corresponding proxy types or through their super types. Take the following .NET snippet as an example:

try
{
    StringArray     arr = new StringArray( 4 );


    arr[ 1867 ] = "test";
}
catch( ArrayIndexOutOfBoundsException oob )
{
    Console.WriteLine( oob.GetMessage().ToString() );
}

The code in the try block throws a Java ArrayIndexOutOfBoundsException. This Java exception is detected by the Codemesh runtime and translated into its corresponding .NET proxy type. An instance of that proxy exception type is then thrown and can be caught by a .NET catch block.

It is important to understand what happens when there is no corresponding .NET exception type available. You (or whoever gave you the .NET classes you are using) might not have included the ArrayIndexOutOfBoundsException in the set of .NET classes. In such a case, the Codemesh runtime will search up the Java exception's inheritance hierarchy until it finds an exception type for which a .NET proxy type exists. If no exception proxy type at all is found, the runtime will throw an JuggerNETProxyException instance which provides some information about the the corresponding Java exception.

The Codemesh runtime does a lot of very sophisticated work for you here. If you wanted to implement the same exception handling model via the JNI API, you would probably be looking at several months of work. Making exceptions work more or less transparently across the language boundary represented a major technical victory for us.

We recommend that you handle JuggerNETEception instances as well as Java exception instances. JuggerNETFrameworkExceptions might also be thrown by the Codemesh runtime to signal framework failures (for example the inability to load a JVM or connect to a Shared JVM server).

To prevent application crashes, you should surround your entire thread procedure (including your Main()) with a try/catch block that handles at least the framework exceptions in a meaningful way. Your main() might look something like this:

static void Main( string args[] )
{
    try
    {
        // here's where you do your actual work
    }
    catch( Throwable t )
    {
        Console.WriteLine( t.ToString() );
    }
    catch( JuggerNETException jne )
    {
        Console.WriteLine( jne.ToString() );
    }
} 

Using such a pattern makes sure that you're not faced with an application crash and that you're receiving some information that is useful for debugging the problem that caused the exception.


Copyright 2006-2011 by Codemesh, Inc., ALL RIGHTS RESERVED

:
frequently asked questions
home products support customers partners newsroom about us contact us