Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Catching' OutOfMemoryError completely solves out-of-memory issue?

I was getting OutOfMemoryError messages in LogCat and my app was crashing because the errors were uncaught.

Two things were causing the OutOfMemoryError:
1. Reading a large text file into a string.
2. Sending that string to my TextView.

Simply adding a catch to these two things not only catches the OutOfMemoryError but appears to completely solve the out-of-memory problem.
No more crashing and no more error messages in LogCat. The app just runs perfectly.

How is this possible? What exactly is happening?


With this code, I was getting the error messages & app crashing:

try
{
myString = new Scanner(new File(myFilePath)).useDelimiter("\\A").next();
} 
catch (FileNotFoundException e) 
{
e.printStackTrace();
}


myTextView.setText(myString);



Just by 'catching' the OutOfMemoryError, no more error messages in LogCat and no crashing:

try
{
myString = new Scanner(new File(myFilePath)).useDelimiter("\\A").next();
} 
catch (FileNotFoundException e) 
{
e.printStackTrace();
}
catch(OutOfMemoryError e)
{
}


try 
{
myTextView.setText(myString);
} 
catch(OutOfMemoryError e)
{
}
like image 929
Eric Glass Avatar asked Oct 03 '22 18:10

Eric Glass


2 Answers

I guess your string isn't loaded completely, or even if it is (it may throw the error just after adding the text), what happens depends on the current memory available for your app so catching OutOfMemoryError isn't a viable solution here.

If you really want to load a large string file and display it in an EditText, I recommend you to load only a small part of the file (let's say 50kB), and implement some kind of paging, like a button which loads the next 50kB. You can also load additional lines as the user scrolls through the EditText.

like image 55
Dalmas Avatar answered Oct 11 '22 20:10

Dalmas


If you catch the OutOfMemoryError, the garbage collector tries to free up the memory previously used and thus the application can carry on if the application will let the garbage collector do its job (i.e. the application has no longer a reference to that large string of yours).

However, catching an OutOfMemoryError is far from fool-proof. See Catching java.lang.OutOfMemoryError?.

like image 36
Tom Avatar answered Oct 11 '22 21:10

Tom