Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        }
    }
like image 696
Waypoint Avatar asked Nov 24 '25 03:11

Waypoint


2 Answers

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
}
like image 108
Frohnzie Avatar answered Nov 26 '25 21:11

Frohnzie


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?

like image 20
gfour Avatar answered Nov 26 '25 19:11

gfour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!