Waypoint
Waypoint

Reputation: 17753

Android NDK - try catch with NoMemoryError

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;
        }
    }

Upvotes: 3

Views: 3207

Answers (3)

Frohnzie
Frohnzie

Reputation: 3569

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
}

Upvotes: 4

Niels
Niels

Reputation: 313

If you trigger an exception/error in your native code you should be able to catch it. However, I would assume that allocating a big chunk of unmanaged memory using malloc or similar will not trigger an error but kill you app the hard way. If you create the same big java array as in your java code instead, however, the java method you call to create the array will fail and create an exception. As exception handling in JNI is very different you have to check for exceptions in your native code manually using something like:

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

Upvotes: 1

gfour
gfour

Reputation: 999

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

Upvotes: 1

Related Questions