This article will state the usage of the “printStackTrace()” method in Java.
What is the “printStackTrace()” Method in Java?
The “printStackTrace()” method in Java is a tool utilized to diagnose exceptions and errors. It is a method of Java’s throwable class that logs all the details associated with the faced exception like line number, class, etc.
Syntax
In the above syntax, this method displays all the details regarding the associated exception.
Example 1: Analyzing the Exception Without Utilizing the “printStackTrace()” Method in Java
In this example, a code with exceptions can be executed without knowing the details of the exception with the help of the “try…catch” statement:
In the above code snippet:
- Specify a “try” block and divide the initialized integer with “0” such that “infinity” is returned.
- The above-discussed step displays an exception which can be handled by the “catch” block and printed on the console.
Output
In the above output, it can be seen that the encountered exception is handled by the “catch” block. But here, the developer doesn’t know where exactly the exception occurred in the code.
Example 2: Analyzing the Exception by Utilizing the “printStackTrace()” Method in Java
In this particular illustration, the “printStackTrace()” method can be associated with the handled exception to log the details of the faced exception via the “try…catch” statement:
In the above illustration:
- Likewise, specify a “try” block and perform the same computation as discussed in the previous example.
- Here, the same exception can be handled by the “catch” block in an effective manner such that the location of the exception can also be displayed via the “printStackTrace()” method.
Output
It can be observed that the location, i.e “line(6)” and “class(Example)” of the exception is also logged on the console.
Conclusion
The “printStackTrace()” method in Java is a tool utilized to diagnose exceptions more appropriately by logging all the details associated with the faced exception like line number, class, etc. This blog discussed the usage and benefit of the “printStackTrace()” method in Java.