There is perfect sense in having an exception barrier at the very top of your call stack, catching and logging all Throwable
s. In server-side code this is in fact the norm. If you make sure to catch the OutOfMemoryError
only at that level, and not anywhere lower, there is a very large chance that it will not harm your system: as the call stack unwinds, all the objects created to serve the request will become unreachable. Since it is very likely that the OOME occurred precisely in the thread which was inflicting the strongest memory pressure on the system, all that memory will be reclaimed and the rest of the system will be able to breathe again.
Yes, technically there's always a chance to get an OOME inside a finally
block, causing a resource leak or worse; or inside some code which was modifying a long-lived, global structure, breaking its invariants, but it is quite unlikely in practice.
When deciding on your policy for OOMEs keep in mind that your application is subject to many unpredictable factors which are more or less likely to deteriorate its stability. OOME is just another point in that spectrum, and typically its risk impact is not particularly high.