How to know about OutOfMemory or StackOverflow errors ahead of time
Anticipating Out of Memory Errors
I'm surprised I didn't see this mentioned in the other posts, but you can use ManagementFactory in Java 5/6 to get at a lot of the memory usage information.
Look at the platform mbean server page for more information on detecting low memory conditions in Java. I believe you can setup notifiers to call code when memory usage reaches a certain threshold.
You can anticipate out-of-memory conditions with Runtime.freeMemory()
and Runtime.maxMemory()
. Most times it'll be hard recovering gracefully, but I leave that to you.
Most StackOverflow errors come out of bad recursion. Unfortunately, the problem of determining if a recursion will stop is generally not decidable (this is a central concept in CS). There are cases, however, you could get warnings, for example some IDEs will let you know if you're invoking a function recursively with no parameters.