1 // Purpose. Java calling C throwing exception 2 // (Java passes int in, C returns nothing or throws exception) 3 ////////////////////////////// JNIdemos.java \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 4 class JNIdemos { 5 private double balance = 100; 6 static { 7 System.loadLibrary( "JNIdemos" ); 8 } 9 static class InsufficientFunds extends Exception { } 10 public double getBalance() { 11 return balance; 12 } 13 public native void withdraw( int amt ) throws InsufficientFunds; 14 public static void main( String[] args ) { 15 JNIdemos account = new JNIdemos(); 16 System.out.println( "balance was " + account.getBalance() ); 17 try { 18 account.withdraw( 50 ); 19 account.withdraw( 70 ); 20 } catch (InsufficientFunds ex) { 21 System.out.println( "withdraw failed"); 22 } 23 System.out.println( "balance is " + account.getBalance() ); 24 } 25 } 26 ////////////////////////////// JNIdemos.cpp \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 27 #include 28 #include "JNIdemos.h" 29 extern "C" { 30 JNIEXPORT void JNICALL Java_JNIdemos_withdraw( JNIEnv* env, jobject this_ptr, 31 jint amt ) { 32 jclass accountClass = env->GetObjectClass( this_ptr ); 33 jfieldID balanceId = env->GetFieldID( accountClass, "balance", "D" ); 34 jdouble balance = env->GetDoubleField( this_ptr, balanceId ); 35 if (amt > balance) { 36 jclass excepClass = env->FindClass( "JNIdemos$InsufficientFunds" ); 37 jmethodID ctorId = env->GetMethodID( excepClass, "", "()V" ); 38 jthrowable excepObj = (jthrowable)env->NewObject( excepClass,ctorId ); 39 env->Throw( excepObj ); 40 return; 41 } 42 balance -= amt; 43 env->SetDoubleField( this_ptr, balanceId, balance ); 44 } 45 } 46 // C:> java JNIdemos 47 // balance was 100.0 48 // withdraw failed 49 // balance is 50.0