What is the printStackTrace() method in Java?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java’s throwable class which prints the throwable along with other details like the line number and class name where the exception occurred.

The printStackTrace() is very useful in diagnosing exceptions. For example, if one out of five methods in your code cause an exception, printStackTrace() will pinpoint the exact line in which the method raised the exception.

svg viewer

Syntax

The syntax of the printStackTrace() method is given below:

public void printStackTrace()
Syntax for the printStackTrace() method

Code

First, consider a case where printStackTrace() is not utilized (in case of an exception):

class Program {
public static void foo() {
try {
int num1 = 5/0;
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main( String args[] ) {
foo();
}
}

Note that the output of the exception shows neither the line number where the error occurred nor the functions that were executed. Now, consider the code snippet below, which uses printStackTrace, and compare its output with the one shown above:

class Program {
public static void foo() {
try {
int num1 = 5/0;
}
catch (Throwable e) {
e.printStackTrace();
}
}
public static void main( String args[] ) {
foo();
}
}

As seen in the output above, the entire stack trace is printed along with line numbers and class names to pinpoint the exact location of the exception. Note that the top-most function in the stack trace is the one that was executed last, hence, that is the function where the exception occurred.

Let’s explore another example where an array index is out of bounds, potentially leading to an ArrayIndexOutOfBoundsException. This commonly occurs when attempting to access an element in an array using an index value that exceeds the array’s length.

class Program {
public static void main(String[] args) {
try {
int[] arr = new int[4];
arr[4] = 3;
} catch (Throwable e) {
e.printStackTrace();
}
}
}

In summary, the printStackTrace() method in Java offers developers a concise means to obtain detailed information regarding exceptions, enhancing the debugging process and fostering effective error resolution.

Copyright ©2024 Educative, Inc. All rights reserved