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

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.

Leave a Comment