Wednesday 26 February 2014

Fill Stack Trace: fillInStackTrace

public Throwable fillInStackTrace()
Fills in the execution stack trace. This method replaces original stack trace with that from the place it is called.

Example: Before adding a call to fillInStacktrace
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){
   e.printStackTrace();
  }
 }
}

 Output
java.lang.ArithmeticException: / by zero
  at StackTraceEx.divide(StackTraceEx.java:5)
  at StackTraceEx.show(StackTraceEx.java:12)
  at StackTraceEx.print(StackTraceEx.java:15)
  at StackTraceEx.main(StackTraceEx.java:20)
  
After adding a call to fillInStacktrace
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){
   e.fillInStackTrace();
   e.printStackTrace();
  }
 }
}

Output
java.lang.ArithmeticException: / by zero
        at StackTraceEx.main(StackTraceEx.java:23)

After calling the method “ fillInStackTrace” The stack trace is replaced by the current stack frame.



Get stack trace                                                 Chained Exceptions                                                 Home

No comments:

Post a Comment