Re: To check or not to check for NULL?
Mike wrote:
Then, the question is- should one even catch "OutOfMemoryError" at all
every time an object is created? What should be the right course of
action? System.exit(1)?
There's a reason that the OutOfMemoryError is an error--you shouldn't
catch it, unless you have a very good reason.
1. Almost anything can generate an OOM error. For example, calling a
function that only puts locals on the stack might do it in extremely
tight situations.
2. The error might not be thrown in a convenient location.
3. What would you do if you caught it? Try to free memory? If that's
what you're thinking, try using Java's SoftReference which interfaces
with the garbage collector itself. If you merely want to die, then the
VM will do it for you if you don't catch. If you want to display an
error message or do other handling, far better to unify it all at a
top-level area (e.g., uncaught exception handlers) since your entire
setup is most likely in pieces anyways.
There's no real point to catching what should be a rare condition when
recovery is impractical and the potential source is nearly every line of
code.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth