If catching an OutOfMemoryError
is highly discouraged, since you may not know the condition of the JVM after catching the error, why doesn't the JVM simply terminate and notify the user somehow instead of throwing the error?
Because there is no single standard way to report an error condition to the user. Throwing an Error allows the object to be caught at the top level, and the report of the condition made however it may be appropriate (console message, write to a log file, displaying a dialog, etc) prior to termination. The documentation states that reasonable applications should not catch Errors, which is true: the best way for them to be handled is in framework code, as there is very little (although not zero) variation in how they can be handled. Specifically, they cannot realistically be recovered from, which is why most application authors attempt to catch them.
Update: there is another reason, too. Throwing an error does not only allow the error to be caught: it also causes code in "finally" blocks to be executed. As these blocks could include critical cleanup code, it is important that they are allowed to run before the application is terminated.
Because you could know what to do and how to do it.
Example: your code (attempts to) create an array with several dozen million elements (depending on some input). Any OutOfMemoryException
will most probably be for this reason. In particular, you can put only the array creation in a try/catch block. After the exception, memory will most probably be in a pretty decent level (the array is either completely allocated, or not allocated at all). Your program can continue executing. Even produce an error message, send an e-mail, or take any other corrective actions and proceed with the next input (from a user, a batch, etc).
That kind of discouragement notes are usually targeted at the beginner/average developer. One that would try to catch the exception at the top level of the program, for example, where there is no detail about what triggered it.
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