Wednesday 26 February 2014

What is a stack trace

A stack trace is a report of all method calls at a particular point of time during the execution of a program. Whenever an error / exception encountered in a program, then by default JVM generates the stack trace.

Example
class StackTraceEx{
 void divide(){
  System.out.println(10/0);
 }

 void show(){
  System.out.println("in show, about call divide ");
  divide();
 }

 void print(){
  System.out.println("in print, about call show ");
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj = new StackTraceEx();
  obj.print();
 }
}
    

Output
in print, about call show
in show, about call divide
Exception in thread "main" java.lang.ArithmeticException: / by zero
  at StackTraceEx.divide(StackTraceEx.java:4)
  at StackTraceEx.show(StackTraceEx.java:8)
  at StackTraceEx.print(StackTraceEx.java:12)
  at StackTraceEx.main(StackTraceEx.java:16)
   
Observe the below statements

Exception in thread "main" java.lang.ArithmeticException: / by zero
                                      at StackTraceEx.divide(StackTraceEx.java:4)
                             at StackTraceEx.show(StackTraceEx.java:8)
                             at StackTraceEx.print(StackTraceEx.java:12)
                             at StackTraceEx.main(StackTraceEx.java:16)

initially main method is called, main calls print, print calls show, show calls divide. “divide(StackTraceEx.java:4)” statements tells that inside divide method the ArithmeticException arises. StackTraceEx.java:4 tells that exception occurred at line number 4. So using stack trace, We can easily debug the Application.

Throwable constructors                                                 print stack trace                                                 Home

No comments:

Post a Comment