Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the JVM simply terminate instead of throwing OOME?

Tags:

java

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?

like image 882
Katona Avatar asked Aug 30 '13 20:08

Katona


2 Answers

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.

like image 165
Jules Avatar answered Oct 19 '22 10:10

Jules


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.

like image 36
Mario Rossi Avatar answered Oct 19 '22 09:10

Mario Rossi