![]() |
VOOZH | about |
The printStackTrace() method in Java is widely used for debugging exceptions. It prints detailed information about an exception, helping developers understand where and why an error occurred during program execution.
Output:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 2
at GFG.main(GFG.java:4)
Explanation:
public void printStackTrace()
The printStackTrace() method provides several overloaded forms that allow developers to print exception stack trace details in different ways
The printStackTrace() method belongs to the java.lang.Throwable class. It prints the complete stack trace of an exception, including:
By default, the output is printed to the standard error stream.
Output:
java.lang.Exception
at GFG.testException1(GFG.java:12)
at GFG.main(GFG.java:4)
Caused by: java.lang.ArrayIndexOutOfBoundsException
at GFG.testException1(GFG.java:10)
Explanation:
public void printStackTrace()
Return Value: This method do not returns anything.
This overloaded version prints the stack trace to a specified PrintStream instead of System.err. It provides flexibility to redirect exception output.
java.lang.Exception: System is Down at GFG.testException1(File.java:35) at GFG.main(File.java:15)
Explanation:
public void printStackTrace(PrintStream s)
This method prints the stack trace to a PrintWriter, often used with StringWriter for logging or storing errors as text. It is especially useful for web applications and log aggregation systems.
Error: java.lang.ArithmeticException: / by zero at GFG.main(File.java:17)
Explanation:
Syntax
public void printStackTrace(PrintWriter s)