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 stream.

Syntax

public void printStackTrace(PrintStream s)

Parameters

s Specify the PrintStream 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.*;

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){
      //print this throwable and its backtrace
      //to System.out
      e.printStackTrace(System.out);
    }
  }
}

The output of the above code will be:

java.lang.ArithmeticException: / by zero
  at MyClass.main(MyClass.java:7)

Example:

Consider one more example to understand the concept better.

import java.lang.*;

public class MyClass {
  public static void main(String[] args){
    try{
      testException();
    }
    catch (Exception e){
      //print this throwable and its backtrace
      //to System.out  
      e.printStackTrace(System.out);
    }
  }

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

The output of the above code will be:

java.lang.Exception: New Exception Thrown
  at MyClass.testException(MyClass.java:15)
  at MyClass.main(MyClass.java:6)

❮ Java.lang - Throwable