Android NDK - try catch with NoMemoryError

android, android-ndk, exception

Solution

In your JNI function you can throw a java exception using the follow snippet. When compiling the native code make sure RTTI and exceptions are enabled.

try {
  int *mega = new int[1024 * 1024];
} catch (std:: bad_alloc &e) {
  jclass clazz = jenv->FindClass("java/lang/OutOfMemoryError");
  jenv->ThrowNew(clazz, e.what());
}

In Java you can simply catch the OutOfMemoryError.

try {
  // Make JNI call
} catch (OutOfMemoryError e) {
  //handle error
}

Problem

I have block of code, which in Android NDK allocates huge ammounts of memory. Last what I need is to use try - catch block for possibility, there might be NoMemoryError. Do you know how to write it in native SDK? I need to implement same functionality as this: ``` for(int i=1;i<50;i++){ try{ int[] mega =new int[i*1024*1024];//1MB }catch (OutOfMemoryError e) { usedMemory= (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory())/new Float(1048576.0); usedText=usedMemory+" MB"; tw.setText(usedText); break; } } ```

Original source

Related problems