How does catching an OutOfMemoryException work?

后端 未结 5 1040
再見小時候
再見小時候 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 12:00

    The reason you can catch an OutOfMemoryException is because the language designer decided to let you. The reason this is sometimes (but not usually) practical is because it's a recoverable situation in some cases.

    If you attempt to allocate a huge array, you may get an OutOfMemoryException, but the memory for that huge array will not actually have been allocated - so other code will still be able to run without problems. Also, the stack unwinding due to the exception may cause other objects to be come eligible for garbage collection, further increasing the amount of memory available.

提交回复
热议问题