Java.lang Package Classes

Java Throwable - printStackTrace() Method



The java.lang.Throwable.printStackTrace() method is used to print this throwable and its backtrace to the specified print writer.

Syntax

public void printStackTrace(PrintWriter s)

Parameters

s Specify the PrintWriter to use for output.

Return Value

void type.

Exception

NA.

Example:

The example below shows how to use the java.lang.Throwable.printStackTrace() method.

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

public class MyClass {
  public static void main(String[] args) throws Throwable {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (Exception e){
      //using a StringWriter to convert
      //trace into a string
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);  
      
      //print this throwable and its backtrace to pw
      e.printStackTrace(pw);

      String error = sw.toString();
      System.out.println("Error is:\n" + error); 
    }
  }
}        

The output of the above code will be:

Error is:
java.lang.ArithmeticException: / by zero
  at MyClass.main(MyClass.java:8)

Example:

Consider one more example to understand the concept better.

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

public class MyClass {
  public static void main(String[] args){
    OutputStream out;
    try{
      testException();
    }
    catch (Exception e){
      //using a StringWriter to convert
      //trace into a string
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);  
      
      //print this throwable and its backtrace to pw
      e.printStackTrace(pw);

      String error = sw.toString();
      System.out.println("Error is:\n" + error); 
    }
  }

  //method to throw Exception 
  public static void testException() throws Exception { 
    throw new Exception("New Exception Thrown"); 
  } 
}

The output of the above code will be:

Error is:
java.lang.Exception: New Exception Thrown
  at MyClass.testException(MyClass.java:26)
  at MyClass.main(MyClass.java:8)

❮ Java.lang - Throwable