Category: Proxy usage

Q

Can I throw Java exceptions from my C++ code?

A

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

try 
{
    if( argc == 1 )
        throw IllegalArgumentException( "argc 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 C++ proxy but it is thrown and handled exclusively on the C++ side.

This is different from what happens in a callback. A callback is a C++ 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( const Message & msg, xmog_localenv * env, xmog_flags flags )
{
    if( TextMessage::dyna_cast( msg ) == null )
        throw IllegalArgumentException( "can only handle TextMessages" );
    ...
}

Don't forget that this is a C++ method that is called from the Java side and that we're throwing a C++ exception here! The Codemesh runtime takes care of this very complicated scenario and translates the C++ 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.

When you're throwing exceptions, it is very important that you understand that C++ has a much more complex exception model than Java. In C++, you can throw anything at all: ints, chars, Foo objects, pointers to Foo objects, etc. The following code snippet will not work as you might expect if your background is predominantly in Java:

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

    ...
}
catch( IllegalArgumentException iae )
{
    ...
}

The problem lies in the fact that you 're throwing a pointer to an exception and you're catching an exception instance. C++ distinguishes between these two cases and the thrown exception pointer will fall through the catch block and probably end up crashing your application. Remove the new to make the above snippet work.


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

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