Q: How to catch an out of memory exception vb.net Seems like a relatively easy question, but i have tried a few things and could not figure out how to catch an exception of type out of memory. Here are a couple things that i have tried:
try

catch ex as exception

if ex = outOfMemoryException then

' do something here

end if

end try



try

catch ex as exception

dim check as new outOfMemoryException

if ex = check then

' do something here

end if

end try

I am using this to display a certain message when an out of memory exception is thrown, so it would be ideal (if possible) to be able to catch this type of exception when it is thrown.
p.s - no i cannot avoid this type of exception because my application is and needs to be able to run on older machines.

A: First of all, this is not how you handle an exception of a given type. Instead, you catch that type:
try
    …
catch ex as OutOfMemoryException
    …
end try

Secondly, you generally don't handle OutOfMemoryException. You can't, because you already ran out of memory and in most situations there is nothing you can do about it, except (carefully, without allocating more memory) logging the error.
OutOfMemoryException (and StackOverflowException) is fatal: when it is thrown, the system informs you of an error but doesn't really give you a chance to fix it.
In some rare cases, you can try freeing some allocated but no longer needed memory. But, especially in the garbage collected world of .NET, this is an exceedingly rare situation.
