Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to catch out of memory exception in java? [duplicate]

I'm developing a program that would require huge amount of memory, and I want to catch when out-of-memory exception happens. I had heard this is not possible to do, but curious if there is any development on this end.

like image 913
jy. Avatar asked Nov 07 '09 06:11

jy.


People also ask

How do you trace out of memory exception?

OutOfMemoryError exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further.

Can we handle out of memory error?

OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang. OutOfMemoryError .

What is out of memory exception?

When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.


2 Answers

It's not an exception; it's an error: java.lang.OutOfMemoryError

You can catch it as it descends from Throwable:

try {     // create lots of objects here and stash them somewhere } catch (OutOfMemoryError E) {     // release some (all) of the above objects } 

However, unless you're doing some rather specific stuff (allocating tons of things within a specific code section, for example) you likely won't be able to catch it as you won't know where it's going to be thrown from.

like image 176
ChssPly76 Avatar answered Sep 20 '22 15:09

ChssPly76


It's possible:

try {    // tragic logic created OOME, but we can blame it on lack of memory } catch(OutOfMemoryError e) {    // but what the hell will you do here :) } finally {    // get ready to be fired by your boss } 
like image 33
Suraj Chandran Avatar answered Sep 21 '22 15:09

Suraj Chandran