Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

try catch - Why is "java.lang.OutOfMemoryError: Java heap space" not caught?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because OutOfMemoryError is an Error, not an Exception. Since OutOfMemoryError isn't a subclass of Exception, the catch (Exception e) doesn't apply.

OutOfMemoryError does extend Throwable, 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...