Android NDK - try catching NoMemoryError

I have a block of code that is allocating huge amounts of memory in the Android NDK. The last thing I need is to use a try-catch block for the possibility, perhaps NoMemoryError. Do you know how to write it to native SDK?

I need to implement the same functionality like 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;
        }
    }

      

+3


source to share


3 answers


In your JNI function, you can throw a java exception using the following snippet. When compiling your own 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 just catch the OutOfMemoryError.

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

      

+4


source


Android is not very friendly to C ++ exceptions (you need to link with a special version of the C ++ library provided by Android for the exception). Maybe you should use malloc () and check its return value to see if the memory allocation was ok?



+1


source


If you are throwing an exception / error in your own code, you can catch this . However, I would guess that allocating a large chunk of unmanaged memory using malloc or the like would not throw an error, but kill you to attach the hard way. However, if you create the same large java array as in your java code, the java method you call to create the array will fail and throw an exception. Since JNI exception handling is very different, you must manually check for exceptions in your own code using something like:

exc = (*env)->ExceptionOccurred(env);
if (exc) ...

      

+1


source







All Articles