JNI and C++ exceptions

Anthony Petrov anthony.petrov at oracle.com
Fri Sep 27 03:05:53 PDT 2013


best regards,

On 09/27/2013 01:46 PM, Mario Torre wrote:
> 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:
> http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html
> """
> 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
> counterparts.
> """
> 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.
> Cheers,
> Mario
> 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

More information about the openjfx-dev mailing list