posted 14 years ago
Yes, it is.
It's risky, because it's possible that memory is still very low at the time you catch the error, and so there's a risk that anything you do might cause a new OutOfMemoryError. However, it may well be better to at least try to handle the error. If it doesn't work, well, you're not really any worse off than if you hadn't caught it. And often you can handle such errors fairly reliably. A common situation is: you call a method that performs some operation that needs a lot of memory, but when the method completes, the memory becomes available again. If an OOME is thrown, you probably don't want to catch that inside the method, because the memory is probably still very low. But catching the error outside the method could work quite well, as by the time you catch the error, one or more key reference variables have gone out of scope, and one or more large objects that were previously not available for GC, now are available for GC. Maybe you can try the method again later, when the machine is less busy. If nothing else, you can log the error, which is probably better than doing nothing.