in reply to Catching "out of memory " error

You can't catch an "out of memory" error. It means what it says: there's no more memory to use! One thing you could try is measuring the amount of memory your process uses as you go and aborting before you run out of memory.