Duplicate :
|
|
Relates :
|
|
Relates :
|
Name: yyT116575 Date: 11/14/2000 java version "1.3.0" Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0) Java HotSpot(TM) Client VM (build 1.3.0, mixed mode) When coupling Java and C++ by means of the JNI, I faced the following problem. A Java program calls a native C++ method through the JNI. This C++ method throws an exception and also catches it again. So, the exception does NOT propagate from the C++ side to the Java side; it remains on the C++ side. Nevertheless, the JVM complains about an unexpected exception in the native code. By the way, this is not a problem with jdk1.3 in a Solaris environment. How to reproduce the problem: ============================= (1) javac TestExceptions.java (2) javah TestExceptions (3) g++ -o libtestx.so -fPIC -shared <jni headers> TestExceptions.C where <jni headers> is -I/usr/local/jdk1.3/include -I/usr/local/jdk1.3/include/linux if you installed jdk under /usr/local (4) Prepend the directory containing libtestx.so (built in step (3)) to the environment variable LD_LIBRARY_PATH (5) java TestExceptions Faulty output: -------------- Boring non-3 MyException thrown! # # An unexpected exception has been detected in native code outside the VM.# Program counter=0x406494ea # # Problematic Thread: prio=1 tid=0x804e328 nid=0x66f runnable # Correct output: --------------- Boring non-3 MyException thrown! MyException caught! Exceptional 3 Boring non-3 Files: ------ // *** File: TestExceptions.java *** public class TestExceptions { private native String threeIsOdd(int number); static { System.loadLibrary("testx"); } public static void main(String[] args) { TestExceptions tx = new TestExceptions(); for (int i = 2; i < 5; i++) { System.out.println(tx.threeIsOdd(i)); } } } // *** File: TestExceptions.C *** #include <iostream> #include "TestExceptions.h" class MyException { public: MyException() {} ~MyException() {} }; JNIEXPORT jstring JNICALL Java_TestExceptions_threeIsOdd(JNIEnv* env, jobject, jint number) { try { if (number == 3) { cout << "MyException thrown!" << endl; throw MyException(); } return env->NewStringUTF("Boring non-3"); } catch (MyException&) { cout << "MyException caught!" << endl; return env->NewStringUTF("Exceptional 3"); } catch (...) { cout << "OtherException caught!" << endl; } return env->NewStringUTF("Should not be reached"); } (Review ID: 112220) ======================================================================
|