Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNA Catching Exceptions

I have a quick question about dealing with exceptions being thrown by libraries under JNA...

When I throw an exception in the underlying native code, JNA gets a invalid memory access error. I'm assuming this is because C libraries cannot throw an exception up through it's stack (it's actually C++/CLR but has C exports)? So is there no real way to report the exception to Java? Or "should it work" and I'm just doing something incredibly wrong?

DllExport void Initialize(char* dir)
{
    throw gcnew System::Exception("Testing");
}

It would be nice for Java to be able to detect these thrown exceptions, and I guess I could actually look into passing a memory pointer into all my C exports and check to see if those are null or not, but seems like a roundabout way.

like image 802
StrangeWill Avatar asked Aug 29 '11 14:08

StrangeWill


People also ask

What is catching an exception?

When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception.

Is the exception that clears a pending exception?

After the native code catches and handles an exception, it can either clear the pending exception so that the computation may continue, or it can throw another exception for an outer exception handler. Many JNI functions may cause an exception to be thrown.


2 Answers

C++ exceptions can only be handled in C++ code. They should never be allowed to escape the C++ world (i.e., a C interface of C++ code should never let exceptions propagate). It is not even safe to let a C++ exception propagate through a layer of C code between two C++ modules (e.g., when a C++ function calls a C function which in turn calls a C++ function).

One of the reasons for this is that there is no standard on how C++ exceptions should be implemented, so C++ modules are only binary-compatible if compiled by the same compiler (in the same version). So code in any other language can't be set up to handle C++ exceptions.

In this case (C++ library, C interface, called from Java) you would have to catch the C++ exception, propagate the information through the C interface (e.g., by using error return codes), check for it in Java and throw an exception there.

like image 57
Philipp Wendler Avatar answered Nov 11 '22 18:11

Philipp Wendler


You need to handle the c++ exception yourself and instead build a java exception which can be passed to the java side of the code.

like image 21
Roger Lindsjö Avatar answered Nov 11 '22 18:11

Roger Lindsjö