Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching OutOfMemoryError

Is there any point catching an out of memory error (java.lang.OutOfMemoryError) in Java?

like image 367
Viren Pushpanayagam Avatar asked Mar 23 '11 10:03

Viren Pushpanayagam


3 Answers

Yes. Here are a few examples where it could make sense:

  • if you want to handle it by gracefully closing your program
  • if you want to display the problem to the user or log the error
  • depending on your design, you might even be able to clear up memory and restore a working state

However, note that normally (unless you're at a spot where you'll be allocating tons of memory at once), you probably wouldn't specifically catch OutOfMemoryError for these cases, but rather do a catch Throwable all the way at the top in your main entry point.

like image 192
Epaga Avatar answered Sep 30 '22 05:09

Epaga


The golden rule is to only catch errors that you can handle. If you can do something useful after an OutOfMemory error, then go ahead.

like image 30
Ingo Avatar answered Sep 30 '22 05:09

Ingo


No, catch Exception and RuntimeException, but hardly ever (changed from 'never') Error:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

Note:
I'm quoting the official Javadocs here. If you don't agree, tell Oracle, don't shoot the messenger :-)

like image 36
Sean Patrick Floyd Avatar answered Sep 30 '22 05:09

Sean Patrick Floyd