Is there any point catching an out of memory error (java.lang.OutOfMemoryError
) in Java?
Yes. Here are a few examples where it could make sense:
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.
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.
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. TheThreadDeath
error, though a "normal" condition, is also a subclass ofError
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With