Idan K Idan K - 4 years ago 154
Java Question

What happens when I throw a C++ exception from a native Java method?

Suppose I'm embedding Sun's JVM in a C++ application. Through JNI I call a Java method (my own), which in turns calls a native method I implemented in a shared library.

What happens if this native method throws a C++ exception?

edit: compiler is gcc 3.4.x, jvm is sun's 1.6.20.

Answer Source

Within the JNI literature, the word exception appears to be used exclusively to refer to Java exceptions. Unexpected events in native code are referred to as programming errors. JNI explicitly does not require JVMs to check for programming errors. If a programming error occurs, behavior is undefined. Different JVMs may behave differently.

It's the native code's responsibility to translate all programming errors into either return codes or Java exceptions. Java exceptions don't get thrown immediately from native code. They can be pending, only thrown once the native code returns to the Java caller. The native code can check for pending exceptions with ExceptionOccurred and clear them with ExceptionClear.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download