Java.lang.Throwable.printStackTrace() Method

Advertisements


Description

The java.lang.Throwable.printStackTrace(PrintWriter s) method prints this throwable and its backtrace to the specified print writer.

Declaration

Following is the declaration for java.lang.Throwable.printStackTrace() method

public void printStackTrace(PrintWriter s)

Parameters

  • s -- This is the PrintWriter to use for output.

Return Value

This method does not return any value.

Exception

  • NA

Example

The following example shows the usage of java.lang.Throwable.printStackTrace() method.

package com.tutorialspoint;

import java.lang.*;
import java.io.*;

public class ThrowableDemo {

   public static void main(String[] args) {

      Throwable t = new IllegalArgumentException("ABCD");
      System.out.println(getStackTrace(t));  
   }
 
   public static String getStackTrace(Throwable t) {
  
      /* prints this throwable and its backtrace to the specified
      print writer. */
      Writer wr = new StringWriter();
      PrintWriter pWriter = new PrintWriter(wr);
      t.printStackTrace(pWriter);
      return wr.toString();
  }
}

Let us compile and run the above program, this will produce the following result:

ava.lang.IllegalArgumentException: ABCD
at ThrowableDemo.main(ThrowableDemo.java:6)



Advertisements
Advertisements