JNI and C++ exceptions

Mario Torre neugens.limasoftware at gmail.com
Fri Sep 27 02:46:39 PDT 2013

Hmm, honestly, this is quite surprising, since afaik in JNI you only
need to check for Java type exceptions if the methods return anything
but a successful condition (that is, in JNI calls obviously), with the
specification requiring that exceptions should be deferred and
explicitly handled in code. Adding a native (C++ specific in this
case) exception to the library would hardly be correct, and in fact
I'm sure it's not:


With C++, the extra level of indirection and the interface pointer
argument disappear from the source code. However, the underlying
mechanism is exactly the same as with C. In C++, JNI functions are
defined as inline member functions that expand to their C

This means the C and C++ APIs are speficied to be the same, to behave
the same, etc... If it were allowed to throw a native exception in C++
you would end up with two different APIs, which is hardly acceptable.

In my opinion this is a bug in this specific vendor platform, not in
JavaFX (or in OpenJDK), and we should not care about that.


2013/9/27 Artem Ananiev <artem.ananiev at oracle.com>:
> Hi,
> here is a short question. In some JDK implementations (e.g. IBM's), JNI may
> throw C++ exceptions. For example, env->NewByteArray() throws bad_alloc.
> Right now in JDK/JavaFX native code we don't protect against that. Should
> we? An anti-pattern that some source scanning tools warn about is
> <type> obj = new <type>();
> if (!obj) {
>   // handle that
> }
> env->SomeJNICall();
> If SomeJNICall() throws an exception, "obj" will never be deleted.
> Protection against bad_alloc doesn't make much sense, since we're out of
> memory anyway and will unlikely be able to recover, but what about other
> exceptions?
> Thanks,
> Artem

pgp key: http://subkeys.pgp.net/ PGP Key ID: 80F240CF
Fingerprint: BA39 9666 94EC 8B73 27FA  FC7C 4086 63E3 80F2 40CF

IcedRobot: www.icedrobot.org
Proud GNU Classpath developer: http://www.classpath.org/
Read About us at: http://planet.classpath.org
OpenJDK: http://openjdk.java.net/projects/caciocavallo/

Please, support open standards:

More information about the openjfx-dev mailing list