Search This Blog

Saturday, May 17, 2014

Simulate Java StackOverFlow Exception



Stack memory:
  Let me describe  high level detail of stack memory, To execute any program we need to allocate two type of memory in processor(RAM).
     One is stack Memory -  The memory used for executing the program in processor.
   Second is Heap Memory- This memory is nothing but to Store the data(Object) in processor.


Stack Memory  will be start used, when program start from main method to the other  method execution.

Example :
Start using stack memory:  main-> method1-> Method 2->..... > Method N
Release stack memory :Method N (execution Over) -> Method N-1 ->  .............. > Method1->main

Below Program  stack memory are not released due to recursive   call of method1(). So it will throw stack over flow exception.




package com.blogspot.microtechinfo;

public class JavaStackOverFlow {

          private static int count=0;
         
          /**
           * @param args
           */
          public static void main(String[] args) {
                   // TODO Auto-generated method stub
                  
                             method1();
                  
          }
          private static void method1()
          {
                  
                   try{
                            
                             System.out.println("count="+ ++count);
                  method1();
                   }
                   catch (Exception e) {
                             // TODO: handle exception
                             e.printStackTrace();
                             System.exit(1);
                   }
                  
                  
          }
         
}


 Output:
  count=4484
count=4485
count=4486
count=4487
count=4488
count=4489
count=4490
Exception in thread "main" java.lang.StackOverflowError
          at sun.nio.cs.SingleByteEncoder.encodeArrayLoop(Unknown Source)
          at sun.nio.cs.SingleByteEncoder.encodeLoop(Unknown Source)
          at java.nio.charset.CharsetEncoder.encode(Unknown Source)
          at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
          at sun.nio.cs.StreamEncoder.write(Unknown Source)
          at java.io.OutputStreamWriter.write(Unknown Source)
          at java.io.BufferedWriter.flushBuffer(Unknown Source)
          at java.io.PrintStream.write(Unknown Source)
          at java.io.PrintStream.print(Unknown Source)
          at java.io.PrintStream.println(Unknown Source)

          at com.blogspot.microtechinfo.JavaStackOverFlow.method1(JavaStackOverFlow.java:21)



No comments:

Post a Comment