How does catching an OutOfMemoryException work?

后端 未结 5 1080
再見小時候
再見小時候 2021-01-01 11:29

I am a little bit confused about the fact that we can just catch an OutOfMemoryException using a try/catch block.

Given the following code:



        
5条回答
  •  长情又很酷
    2021-01-01 11:50

    The GC makes an analysis on the references that are used in the program, and can throw away any object that isn't used anywhere.

    An OutOfMemoryException doesn't mean that the memory is completely depleted, it just means that a memory allocation failed. If you tried to allocate a large memory area at once, there may still be plenty of free memory left.

    When there isn't enough free memory for an allocation, the system does a garbage collection to try to free up memory. If there still isn't enough memory for the allocation, it will throw the exception.

    A StackOverflowException is not possible to handle, because it means that the stack is full, and it's not possible to remove anything from it as it is with the heap. You would need more stack space to continue running the code that would handle the exception, but there is no more.

提交回复
热议问题