OutOfMemoryError, how to catch?

In my application, whenever I load this one file I always get a OutOf MemoryError, java heap space…

I know why, its becasue the image is 4000pixels by 4000pixels…

Which i know i have no real reason to load this, but how would i catch this error so that i can keep the program running smoothly?

Try something like this:


try
{
    File f = ....
    ...... //Load file in here
    ......
}
catch (OutOfMemoryError e)
{
    e.printStackTrace();
}

You can’t cleanly catch an OutOfMemoryError, or any Error. That’s the difference between an Error and an Exception.

EDIT:
The only thing you can do is prevent an OOME from happening by:

  1. Increase the maximum heap space to what your program needs by using the -Xmx parameter.
  2. Make sure you are not having an object leak (keeping references to unused objects by mistake, typically in Collections).

Your image will take about 64Mb of memory. Are you sure you really need such a huge image? If loading such a large image is absolutely necessary for your program, just increase the max heap size with -Xmx.

well… like i said, in reality there shouldnt be any reason for the person to try to load a image that size…
Is there some way I can scan the file before it loads it into the system?

Like a way to view the size of the file, and if it is over the heap size, dont allow the user to upload the file?

Is there a way to call -Xmx from within the program, or does this have to be done at the batch file before the program starts?

You can use File.length() for that and the methods in Runtime.getRuntime().

You can’t change the max heap space from within the program. You can only set it using the -Xmx VM argument.

I also came across an interesting article about this matter that might be of use:
http://www.roseindia.net/javatutorials/OutOfMemoryError_Warning_System.shtml