Friday 28 February 2014

Extract information from StackTraceElement

StackTraceElement class provides method to extract the class name, method name, line number , file name from the given stack trace element.

public String getClassName()
Returns the fully qualified name of the class

public String getMethodName()
Returns the name of the method containing the execution point represented by this stack trace element.

public String getFileName()
Returns the name of the source file containing the execution point represented by this stack trace element.

public int getLineNumber()
Returns the line number of the source line containing the execution point represented by this stack trace element.

Example
class StackTraceEx{
 void divide(){
  try{
   int val = 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){
   StackTraceElement[] trace = e.getStackTrace();
   for(int i=0; i < trace.length-1; i++)
    System.out.println(trace[i].getClassName() +" " + trace[i].getFileName() +" " + trace[i].getMethodName() +" " + trace[i].getLineNumber());
   }
  }
}


Output
StackTraceEx StackTraceEx.java divide 15
StackTraceEx StackTraceEx.java show 22
StackTraceEx StackTraceEx.java print 25
   


Create stack trace element                                                 Threads in Java                                                 Home

No comments:

Post a Comment