Prerequisite knowledge of the following Java programming topics:
Convert Stack Trace to String
In the program below, we’ve dropped an ArrayIndexOutOfBoundsException to our program by accessing an out-of-bounds element. The Java StringWriter class is a character stream that collects the output from the string buffer that can be used to construct strings. The Java PrintWriter class is a part of the java.io package which is used to write output data in the form of text. Using StringWriter and PrintWriter in the catch block, and the purpose behind it is to print the given output in the form of a string.
Now print the stack trace using the printStackTrace() method of the exception and after that write it in the writer. And finally, convert it into a string using the toString() method.
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3 at PrintStackTrace.main(PrintStackTrace.java:12)
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.