The general advice is that you should not catch java.lang.Error except in special circumstances, see Is it a bad practice to catch Throwable? for instance.
My situation is that I have a program which sometimes runs out of memory and throws java.lang.OutOfMemoryError. Although there's no recovery from this I do want to know it happened, so I wish to see something in the log and a non-zero exit code. So is something like this adviseable?
public static void main(String[] args)
{
try
{
...
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
catch (OutOfMemoryError e)
{
e.printStackTrace();
System.exit(1);
}
}
Another program is similar except that it may be one particular thread that is consuming all the memory. In this case if that thread exits it is possible to continue processing, again all I really want is to see a log and to ultimately have a non-zero exit code. So should I catch the OutOfMemoryError in that threads run method?