Wednesday 26 February 2014

Get the stack trace : getStackTrace()

public StackTraceElement[] getStackTrace()
Returns an array of stack trace elements, each representing one stack frame. The zeroth element in the Array represents the top of the stack frame, for ex, where the error occurred, The last element in the Array represents the start frame of the Execution.

Example
class StackTraceEx{
 void divide(){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   throw e;
  }
 }

 void show(){
  divide();
 }

 void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  
  try{
   obj.print();
  }
  catch(Exception e){
   System.out.print(e + " Occurred in the method ");
   StackTraceElement[] trace = e.getStackTrace();
   for(int i=0; i < trace.length-1; i++)
    System.out.print(trace[i].getMethodName() +" Called by method ");
    System.out.print(trace[trace.length-1].getMethodName() +" in the class " + trace[trace.length-1].getClassName());
  }
 }
}

Output
java.lang.ArithmeticException: / by zero Occurred in the method divide Called by
 method show Called by method print Called by method main in the class StackTrac
eEx

StackTraceElement represents a single stack frame. It provides various utility methods to extract method name , line number, class name etc., from the stack frame.


print stack trace                                                 Fill stack trace                                                 Home

No comments:

Post a Comment