How to Handle OutOfMemoryError in Custom exception class? Why would you want to catch an OutOfMemoryError? If an OutOfMemoryError is generated by the JVM, there is not much you can do, so what use is theOutOfMemoryError?






Encountering an OutOfMemoryError means that the garbage collector has already tried its best to free memory by reclaiming space from any objects that are no longer strongly referenced. If it could not reclaim enough space, then it also tried to obtain memory from the underlying operating system, unless heap space is already at the JVM upper memory bound set by the -Xmx parameter (-mx in JVMs prior to Java 2). So encountering theOutOfMemoryError means that there is no more heap space that can currently be reclaimed, and that either the operating system cannot provide any more memory to the JVM or you have reached the JVM upper memory bound. In any case, there is not much you can do, so when would you ever want to catch an OutOfMemoryError?
The following sections describe a few special situations when it can be useful to catch an OutOfMemoryError.
Expanding Memory and Determining Memory Limits this two feature we need OutOfMemoryError in try catch block.

package com.kartik.error;
/**
 * 
 * @author Kartik Chandra Mandal
 * How to handle run time exception in Java file
 */
public class RunTimeMemoryException {
private static final int MEGABYTE = (1024*1024);
public static void runOutOfMemoryError() throws Exception{
 MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
try {
      long data[] = new long[1000000000]; 
    }
    catch (Exception e) {
     throw new Exception("Out of memory error e");
    }catch (OutOfMemoryError e) {
            MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
            long maxMemory = heapUsage.getMax() / MEGABYTE;
            long usedMemory = heapUsage.getUsed() / MEGABYTE;
            System.out.println( "Memory Use :" + usedMemory + "M/" + maxMemory + "M");
         throw new Exception("Out of memory error by Kartik");
        }
}
public static void main(String[] args) {
try {
runOutOfMemoryError();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Out Put:

 Memory Use :1M/882M
Out of memory error by Kartik
java.lang.Exception: Out of memory error by Kartik
at com.demo.RunTimeMemoryException.runOutOfMemoryError(RunTimeMemoryException.java:21)

at com.demo.RunTimeMemoryException.main(RunTimeMemoryException.java:28)
Previous
Next Post »

1 comments:

Click here for comments
23 October 2016 at 08:21 ×

where is base exception.

Congrats bro amit singh rana you got PERTAMAX...! hehehehe...
Reply
avatar