Home >Java >javaTutorial >When Should You Catch a Java OutOfMemoryError?
Catching java.lang.OutOfMemoryError?
The Java documentation advises against catching java.lang.Error, including java.lang.OutOfMemoryError. However, there are situations where doing so may be justified.
When to Catch OutOfMemoryError
Consider catching OutOfMemoryError only for graceful termination, releasing resources and logging the failure cause. It occurs when a block memory allocation fails due to insufficient heap resources. Yet, the heap still contains allocated objects. By dropping references to runtime objects, more memory can be freed for cleanup.
Avoiding Memory Allocation in Catch Handler
To prevent further memory allocation in the catch handler, consider:
Example Code
The following code demonstrates catching OutOfMemoryError and freeing memory for cleanup:
import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; public class OutOfMemoryErrorHandling { private static final int MEGABYTE = (1024 * 1024); public static void main(String[] args) { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); for (int i = 1; i <= 100; i++) { try { byte[] bytes = new byte[MEGABYTE * 500]; } catch (OutOfMemoryError e) { // Cleanup operations: // Drop references to runtime objects // Release external resources (e.g., logging) MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); long maxMemory = heapUsage.getMax() / MEGABYTE; long usedMemory = heapUsage.getUsed() / MEGABYTE; System.out.println(i + " : Memory Use :" + usedMemory + "M/" + maxMemory + "M"); } } } }
Conclusion
Catching OutOfMemoryError should be approached with extreme caution and only to facilitate graceful termination. By carefully managing memory allocation in the catch handler, it is possible to avoid further memory issues and allow for proper cleanup before the JVM exits.
The above is the detailed content of When Should You Catch a Java OutOfMemoryError?. For more information, please follow other related articles on the PHP Chinese website!