Wednesday 26 February 2014

Printing Stack traces : printStackTrace

Throwable class provides printStackTrace method to get the stack trace information for a Throwable object. The Throwable object may be an error or Exception.

public void printStackTrace()
Prints this throwable and its backtrace to the standard error stream. PrintStackTrace() has two other forms also like printStackTrace(PrintStream s), printStackTrace(PrintWriter s). One for to write trace to a print stream,and other for to a print writer.

The implementation of printStackTrace (), looks like below. It is simply calling the overloaded method printStackTrace(PrintStream s) by passing System.err as an argument.

public void printStackTrace() {
      printStackTrace(System.err);
}
  
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){
   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)
 
Other Overloaded methods
public void printStackTrace(PrintStream s)
Prints this throwable and its backtrace to the specified print stream.

public void printStackTrace(PrintWriter s)
Prints this throwable and its backtrace to the specified print writer.


Stack trace                                                 Get stack trace                                                 Home

No comments:

Post a Comment