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:
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.