Category: Proxy usage

Q

Can I throw Java exceptions from my .NET code?

A

Yes. It's really easy and it works under all circumstances. The following .NET snippet illustrates this.

try 
{
    if( args.Length == 1 )
        throw new IllegalArgumentException( "args.Length needs to be >= 2" );

    ...
}
catch( RuntimeException rte )
{
    ...
}

This exception is not thrown on the Java side; it is created on the Java side and wrapped in a .NET proxy but it is thrown and handled exclusively on the .NET side.

This is different from what happens in a callback. A callback is a .NET method that is invoked from the Java side, for example a JMS onMessage() implementation. What happens when you throw an exception from a callback method? Take the following snippet as an example:

void OnMessage( Message msg )
{
    if( TextMessage.From( msg ) == null )
        throw new IllegalArgumentException( "can only handle TextMessages" );
    ...
}

Don't forget that this is a .NET method that is called from the Java side and that we're throwing a .NET exception here! The Codemesh runtime takes care of this very complicated scenario and translates the .NET exception into a Java exception. It then throws the Java exception into the JVM. This is the right thing to do, but it means that the calling Java code has to be ready to handle the thrown exception. That burden is on you or whoever wrote the calling Java code.


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

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