Java Program to Print Stack Trace
Consider a bookshelf in which books are placed one over another. Now if the person wants to read the book which he placed first, in order to do so all books over the first book are needed to be removed to reach out to the desired book. That is the book that was placed first at the beginning itself. The method by which the computer stores books known as elements in such a fashion is called Stack.
It is an abstract data type which has the following operations: Operations Action
push() Inserting elements pop() Deleting elements isEmpty() To check if the stack is empty isFull() To check if the stack is already full top() OR peek() To access top element from the stack
Now as per the functions in Stacks, an exception is thrown in 3 cases:
- If the stack is full when push is called
- Pop to remove and return the value at the top of the stack.
- If the stack is empty when pop is called.
In order to print the exception, there is a method for this data structure known as printstackTrace(). It is used in the Exception handler of a particular Exception to handle the Exception. This is a method of Java’s throwable class that prints the throwable Exception object as well as with other Information like the line number where Exception occurs and class name where the exception occurred. Throwable is super-class for all exception classes.
Both the stack traces are discussed below:
- Single Line Stack trace
- Multi-Line Stack trace
A. Single Line Stack trace: Most of the generic exceptions fall in this category. There are several exceptions but in order for implementation part ‘ArrayIndexOutOfBound‘ is taken into consideration for implementation
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 at GFG.main(File.java:9)
B. Multi–Line Stack Trace: This condition occurs when we call the function inside into another function and if any function throws Exception retrace all the path where it calls with the printstackTrace() Method.
java.lang.ArithmeticException: / by zero at GFG.check2(File.java:11) at GFG.check(File.java:7) at GFG.main(File.java:19)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.