I have a thread in a Java web application that causes a java.lang.OutOfMemoryError: Java heap space exception, but the try/catch block does not catch the error.
Sample code:
private void doSomeWork()
{
try
{
processData(); //Causes OutOfMemoryError
System.out.println("This line does not execute");
}
catch (Exception e)
{
System.out.println("Exception. This line does not execute.");
//Log error
}
finally
{
System.out.println("finally. This line does execute");
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
Output:
finally. This line does execute Thread name: _Worker-8 Exception in thread "_Worker-8" java.lang.OutOfMemoryError: Java heap space ...
Background:
I recently took over this Java project and I’m trying to get up to speed with Java and this project. I’m a C# developer, so I’m not yet familiar with this project or Java.
I know I can fix the error using the -Xmx setting, but I’m interested in catching this error so I can log it. The error is not showing up in any of the logs files, and the output is being shown in the console in debug mode in Eclipse.
Because
OutOfMemoryErroris anError, not anException. SinceOutOfMemoryErrorisn’t a subclass ofException, thecatch (Exception e)doesn’t apply.OutOfMemoryErrordoes extendThrowable, however, so you should be able to catch it. Here’s a SO discussion on when (if ever) you should catch Errors. Generally, since you can’t do anything about it, the recommendation is to not bother catching Errors in production code. But given a special case where you’re trying to debug what’s going on, it might be helpful.