Print stack trace in Java



In order to print the stack trace in Java, we use the java.lang.Throwable.printStackTrace() method. The printStackTrace() method prints the throwable and its backtrace in the standard error stream.

Declaration - The java.lang.Throwable.printStackTrace() method is declared as follows −

public void printStackTrace()

Let us see a program to print the stack trace in Java.

Example

 Live Demo

public class Example {
   public static void main(String args[]) throws Throwable {
      try {
         int n = 3;
         System.out.println(n/0);
      } catch (ArithmeticException e) {
         System.out.println("Printing stack trace...");
         e.printStackTrace(); // prints the stack trace
      }
   }
}

Output

Printing stack trace...
java.lang.ArithmeticException: / by zero
at Example.main(Example.java:8)

Advertisements